Fatih YILMAZ
Fatih YILMAZ

Reputation: 43

ArrayList in java

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

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

How can I add veri2 to veri1 like one element? I mean, if I call veri.get(0), it returns veri2.

Upvotes: 3

Views: 6096

Answers (7)

Jonas Fagundes
Jonas Fagundes

Reputation: 1519

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);

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

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.

Upvotes: 2

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116306

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.

Upvotes: 15

Brent Parker
Brent Parker

Reputation: 739

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);

Upvotes: 0

Scott
Scott

Reputation: 4220

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);

Upvotes: 1

Uri
Uri

Reputation: 89859

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.

Upvotes: 2

Daff
Daff

Reputation: 44215

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);

Upvotes: 5

Related Questions