Hi is there a standard place for accessing empty array constants in the JDK > 1.5.
When I want to do a conversion from a String Collection (e.g. ArrayList)to a String Array I find myself using my own
which is defined in my own Constants class:
public static final String[] EMPTY_STRING_ARRAY = new String[0];
And then in my client code something like:
String[] retVal = myStringList.toArray(Constants.EMPTY_STRING_ARRAY);
return retVal;
I was wondering if this is the "idiomatic" way of doing it or if I'm missing something
I get the impression from the brief search I did that this kind of thing is prevalent in many people's code.
Any ideas, answers, comment (aside from that I shouldn't really use String Arrays) greatly appreciated,
Cheers
Simon
I would recommend the following code improvement :
String[] retval = myStringList.toArray(new String[myStringList.size()]);
This way, the toArray method uses the provided, appropriately-sized array as a container, instead of creating a new one behind the scenes. From the ArrayList javadoc :
If the list fits in the specified
array, it is returned therein.
Otherwise, a new array is allocated
with the runtime type of the specified
array and the size of this list.
There are no array definitions like that in the JDK anywhere. The only two standard ways of doing it in the JDK are that which you list or
String ret[] = new String[myStringList.size()];
myStringList.toArray(ret);
return ret;
Related
I'm still new to java and writing/reading code, so I'm not quite sure what my professor wants. All I need is some reinforcement of what I should be doing.
The assignment is as follows:
Specify and then implement a method (of some class X) that is passed a NumberList and that returns an array containing the values from the NumberList.
(The NumberList is not changed by your method. Your method is NOT a member of NumberList. You won't be able to test your method by running it since I am not providing the NumberList class to you.)
If you need it, here are the public methods.
The one method that I use is:
public int size() //returns number of items in this NumberList
So, as I understand, all I am doing is taking the NumberList and creating an array of the values. Easy enough. Is this handling the work that is asked?
public double [] arrayNL(NumberList list){
//pre: NL is not empty
//post: array with NL values is returned
double [] arrayNL = new double [list.size()];
for(int x=0;x<list.size();x++){
arrayNL[x]=list.nextDouble;
}
return arrayNL;
}
Just uncertain about list.size() and list.nextDouble... and that is if I'm correct in understanding the problem. Really haven't done enough object coding to be familiar/confident with it and I heavily rely on testing, so I'm questioning everything. Any help would be great, I just have trouble following this professor's instructions for some reason.
Not sure I understand the question. Is the goal to write the code that copies the list to the array, or to implement the methods in the NumberList class based on the pre- and post- conditions?
I believe that one of the goals of this exercise is to teach how to read an API (Application program interface) and implements its method just by reading the documentation, without reading the actual code behind it.
This is an important practice since as a future developer you will have to use other people's methods and you won't be able to implement everything by yourself.
As for your code, I'm not sure where you've seen the nextDouble method as I don't see it in the documentation. Unless it was given to you, I suggest you'll stick to the documentation of NumberList() and other basic coding features.
Instead of using nextDouble you can use: public double get(int index) so your for loop would look something like this:
for(int i = 0; i < list.size() ;i++){
arrayNL[i]= list.get(i);
}
The rest of your code is basically fine.
Your code is basically all there, although next double is undefined in the NumberList class so that may give you trouble. Here's what each part is doing:
public double [] arrayNL(NumberList list){
// Initialize an array of doubles containing the same # of elements
// as the NumberList
double [] arrayNL = new double [list.size()];
// Iterate through the NumberList
for(int x=0;x<list.size();x+) {
// Copy the double from the NumberList object to the double array
// at the current index. Note "nextDouble" is undefined, but
// NumberList does have a method you can use instead.
arrayNL[x]=list.nextDouble;
}
// After iterating through the whole list, return the double array
return arrayNL;
}
Sorry for any formatting issues. Typed this on my phone
Using Roslyn for VB.Net I can get the Type of an Expression using the code below.
Dim ExpressionType As TypeInfo = SemanticModel.GetTypeInfo(ForEachStatement.Expression)
If the expression is a collection (List, Dictionary, Array, Collection...) how can I find out what is in the collection? For the example below I want to find DocumentIdAndRoot
Dim docs As List(Of DocumentIdAndRoot) = Await RemoveParameterAsync(document, parameter, root, cancellationToken)
If your question is specific to foreach, then you should use SemanticModel.GetForEachStatementInfo(), which returns a ForEachStatementInfo with all the necessary information.
What you could do is take the TypeInfo you get, and look at the ImplementedInterfaces property. One of those would be IEnumerable or ICollection, and from there you could look at what the generic parameter is.
If you do have a ForEach involved somewhere, you're still better off using Tamas' approach, since that will correctly implement the language rules there.
I'd like to implement a method which allows me to access a property of an unknown/anonymous object (-graph) in a late-bound / dynamic way (I don't even know how to correctly call it).
Here's an example of what I'd like to achieve:
// setup an anonymous object
var a = new { B = new { C = new { I = 33 } } };
// now get the value of a.B.C.I in a late-bound way
var i = Get(a, "B.C.I");
And here's a simple implementation using "classic" reflection:
public static object Get(object obj, string expression)
{
foreach (var name in expression.Split('.'))
{
var property = obj.GetType().GetProperty(name);
obj = property.GetValue(obj, null);
}
return obj;
}
What other options do I have with C# / .NET 4 to implement something similar as shown above, but maybe simpler, more performant, etc.?
Maybe there are ways to achieve the same thing, which would allow me to specify expression using a lambda expression instead of a string? Would expression trees be helpful in any way (e.g. as shown in this question)?
Update: the object and the expression are passed into my code via a web service call. That's why I used object and string in my Get() method.
Do you actually only have the expression as a string? Is it known at compile-time, just that the types themselves aren't known (or are hard to express)? If so:
dynamic d = a;
int i = d.B.C.I;
If you really only have it as a string (e.g. as user-entered data) that makes life a lot harder, and none of the C# 4 features really help you. You could potentially evaluate it as an IronPython script or something like that...
EDIT: Okay, after the update it sounds like you're in the latter situation - in which case, I don't know of a nicer way than using reflection. Some of the built-in property binding built for UIs may help, but I don't know of a clean way of accessing it.
If you want to use C# style, you could use the Mono compiler as a service from your application. I describe how to do this here:
Mono Compiler as a Service (MCS)
As an alternative approach, you could use reflection to put all of your object's properties into an ExpandoObject then use it like a dictionary (because ExpandoObject implements IDictionary). Alternatively, you could use JSON.NET and call JObject.FromObject, which will turn a regular object into a JObject which is accessible in a dictionary-like style (and as an added benefit has recursive graph support). Lastly, you could use the same approach to dump your object into a dictionary of dictionaries.
I have an arraylist that contains urls in the form similar to :
stackoverflow.com/questions/ask/hello
stackoverflow.com/questions/ask
stackoverflow.com/questions
stackoverflow.com/
If I only wanted to keep the first one and remove the rest, how would I go about doing that since technically they are not duplicates.
I thought of using substring manipulation but not to sure how to implement that.any ideas appreciated.
Assuming I understand the question correctly, you can accomplish this by looping through your ArrayList, building a list of found domains, and simultaneously outputting a new list only when the found domain is not already a member of that first list.
Or, you could build a dictionary of domain to url by iterating through the ArrayList in reverse. Since a dictionary can only have one value per key, the URLs will overwrite themselves in the dictionary and you will only have one URL per domain. Since you iterated in reverse, you will be left with a dictionary containing the first match in the ArrayList. You could then use LINQ to grab just the values (e.g. MyDictionary.Select(elem => elem.Value)).
An example implementation of the second way I mentioned (in C#, you can convert it) is:
Dictionary<string, string> MyDictionary = new Dictionary<string, string>();
foreach(string Url in MyArrayList.Reverse())
MyDictionary[Url.Split("/")[0]] = Url;
There are dozens of ways you could accomplish this task. These are just two examples.
Hmmm I'm not sure if i titled this question properly or am asking it properly, but here goes.
I've got serialized objects (in XML) stored in a database, along with a string/varchar indicating the type.
Right now i am doing this: (because i have a finite number of different types)
Dim deserializer as XmlSerializer
If datatable("type") = "widget1" then
deserializer = new XmlSerializer(GetType(Widget1))
elseif datatable("type") = "widget2" then
deserializer = new XmlSerializer(GetType(Widget2))
...
i'd like to do something like
Dim deserializer as XmlSerializer
deserializer = new XmlSerializer(MagicallyConvertToSystemDotType(datatable("type"))
Am i barking up the wrong tree here?
Have you tried using Type.GetType? This takes a string parameter and returns a type for that name. You may have to give it additional information about the simple name "widget" and more along the lines of a full name. But it appears from your sample they should all have the same namespace so that shouldn't be a big hurdle.
The other option if you want an actual keyword Type to work with, and not a variable type is using something like (sorry I'm using C# and am too tired to do the VB conversion):
method in XmlSerializer like Deserialize(typestring, object);
method in XmlSerializer like Deserialize<T>(object);
public void Deserialize(string typestring, object obj)
{
MethodInfo deserialize = typeof(XmlSerializer)
.GetMethod("Deserialize", BindingFlags.Instance | BindingFlags.Public)
.MakeGenericMethod(new Type[] { Type.GetType(typestring) });
deserialize.Invoke(this, new[] { obj });
}
Specifically, I think you're looking for this code here (NOTE: I don't work much in VB.Net, so I hope everything there is syntactically correct):
VB.Net:
// Get the type of object being deserialized.
Dim t as Type = Type.GetType(typeNameString);
// Make a new instance of the object.
Dim o as Object = Activator.CreateInstance(t);
C#:
// Get the type of object being deserialized.
Type t = Type.GetType(typeNameString);
// Make a new instance of the object.
object o = Activator.CreateInstance(t);
Edit (26 Oct, 2009, 15:10 GMT-0600): The Type.GetType(string typeNameString) method does not always recognize types as simply their fully qualified name. It would be in your best interest to be sure and include as much information as you can in your parameter string, as follows:
VB.Net/C#:
typeNameString = objectSerialized.GetType().Namespace + ", " + objectSerialized.GetType().Name + ", " + objectSerialized.GetType().Assembly.FullName
Less specifically, I just had the same problem, and after a lot of research, I finally came up with a nice solution for handling all most of this dynamically. I've posted the entire source code to a class capable of serializing and deserializing objects of any type not containing generics or arrays using Reflection. Feel free to take it and use it as your own. If anyone decides to add the handling for generics and arrays, please send me an updated copy so I can post it back on my blog (and you'll get an honorable mention ;-)...). It will serialize everything recursively, and has some special coding in there for enums as well.
Take a look and see if that covers everything you're looking for at:
http://maxaffinity.blogspot.com/2009/10/serialize-objects-manually.html
~md5sum~
Edit (27 Oct, 2009 14:38 GMT-0600): Corrected some misinformation about the class available from my blog.