开发者

ArrayList in java

ArrayList<String> veri1 = new ArrayList<String>();

String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

How can I add veri2 to 开发者_如何学Goveri1 like one element? I mean, if I call veri.get(0), it returns veri2.


You should declare your list as a list of string arrays, not a list of strings:

List<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

veri1.add(veri2);

Note that in general it is better to declare your list as List instead of ArrayList, as this leaves you the freedom to switch to a different list implementation later.


You should use the List interface and generics (for Java >= 1.5). Depending on what you want to do you can use this:

String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

List<String> veri1 = new ArrayList<String>();
veri1.addAll(Arrays.asList(veri2)); // Java 6

List<String[]> veri3 = new ArrayList<String[]>();
veri3.add(veri2);


You can't actually do this.

veri2 is an array of strings, veri1 is an arraylist of individual strings Thus, doing veri1.get(0) should return a single string, not an array of strings.


I just saw (due to fm), that you have an ArrayList<String>. You can do:

ArrayList veri1 = new ArrayList();
veri1.add(veri2)

or

ArrayList<String[]> veri1 = new ArrayList<String[]>();
veri1.add(veri2)

You can also make ver1 a List, which gives you flexibility in changing implementations.


It all depends on whether or not you want your ArrayList to be of one type or if you need it to hold multiple types.

If you just need it to hold String arrays throughout your code, declare as stated above:

ArrayList<String[]> list1 = new ArrayList<String[]>();

then just add the String array to it as follows:

list1.add(stringArray);

If you want it to be dynamic, declare it with the object type:

ArrayList<Object> anythingGoes = new ArrayList<Object>();

and then you can add anything later on as well:

anythingGoes.add(stringArray);
anythingGoes.add(myAge);
anythingGoes.add(myName);


I think you mean this:

import java.util.Arrays;

ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

veri1.addAll(Arrays.asList(veri2);


You pretty much just need to add the array to the ArrayList.

ArrayList<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"a", "b", "c"};
veri1.add(veri2);

System.out.println(veri1.size());
for(String[] sArray : veri1)
    for(String s : sArray)
        System.out.println(s);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜