开发者

Paramertized Types

I am from开发者_JAVA百科 a .Net background and do not understand the following snip. Can someone explain the <> and the following code to me as I just dont seem to get it. Sorry for dumb questions but this one I have been trying to understand all evening.

List<double[]> x = new ArrayList<double[]>();

for (int i = 0; i < 3; i++) {
  x.add(new double[] { 1, 2, 3, 4, 5, 6 });
}


They're the equivalent of C# generics. It's creating a list of double arrays, then adding [1,2,3,4,5,6] to it three times.


If you create a List<T> you can add instance of T to the list. In this case, T is double[].


In the Java programming language arrays are objects and may be assigned to variables of type java.lang.Object. Your code can also be written this way

Object numbers =new double[] { 1, 2, 3, 4, 5, 6 };

Your code

List<double[]> x = new ArrayList<double[]>();

for (int i = 0; i < 3; i++) {
  x.add(numbers);
}

Another variation: Here I created "x" as a List that can contain Object types. Since, arrays are subclasses of Object in Java, I can store the arrays in this list "x"

List<Object> x=new ArrayList<Object>();

for (int i = 0; i < 3; i++) {
    x.add(numbers);
}


For a list, the type parameter in the <>'s indicates what type of objects should be stored in that list. List<double []> creates a list that stores arrays of doubles.

List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});

Would add two double arrays to myList. So: myList.get(0) would return: {1,2,3} and myList.get(1) would return: {4,5,6}.

If you are trying to just create a list of doubles, and not a list of double arrays, you would do:

List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);

Now myList.get(0) will return 1 and myList.get(1) will return 2. Notice that to create a list of a primitive type, you need to specify the object version of that primitive type in the type parameter. I.e., you can't do: List<double>

This is because all type parameters just get converted to Object by the compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜