Inserting a String[] into a String[] in Java? - java

How do you add a String[] into a String[] in Java? To be more clear, my desired output is:
String[][] out = {{"A", "AA"},{"B", "BB"}};
I don't know the size of the output array, it can contain more then two elements. Basically, I wanted to do it like this (don't mind the syntax it's a blend of Python):
String [] out;
String[] temp = {"A","AA"};
out.append(temp)
So now out should look like {{"A","AA"}}. Then I can append {"B", "BB"} creating the desire output above? This is what my thought was, but I'm not sure if it can be done. I am more experienced with Python and it can be done in Python, but I am wanting to do this in Java. Any ideas?

As in the comment mentioned, you can use the List to store all the array values inside.
It is when you put in:
List<String[]> list = new ArrayList<>();
String[] array = {"A", "B"};
list.add(array);
...
And it is when you get out:
String[] array = list.get(0 /*i*/);

Try using List for this purpose as you would have more operations to perform on Lists than an Array.
List<List<String>> out = new ArrayList<>();
List<String> temp = new ArrayList<String>();
temp.add("A");
temp.add("AA");
out.add(temp);
Read through the Javadocs for more on this.

You can either use List or ArrayList that dynamically grows.
ArrayList al = new ArrayList();
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
For differences between List and ArrayList Type List vs type ArrayList in Java
Detailed Methods of ArrayList
You could try this way too if you exactly want to add dynamic array of Strings into another dynamic array.
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);

Because in Java, Array is a fixed length data structure so you should try java List which supports dynamically insertion and deletion of elements. An example using java.util.ArrayList is following:
java.util.List<String[]> out = new java.util.ArrayList<String[]>();
String[] temp = {"A","AA"};
out.add(temp);//insertion
And using index (started from 0), we can get element like out.get(0); and can remove element like out.remove(0);

Related

Converting List<List<String>> to array

I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}

Collections.sort() affects all ArrayLists. How do I sort only one list and not the others?

I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.

Is there a difference between List<String> A = new ArrayList<String> ( ) and ArrayList<String> A = new ArrayList<String>()?

String[] somestringarray = { "a","b","c"};
Also,
List<String> A = new ArrayList<String>(Arrays.asList(somestringarray));
is Arrays.asList() a collection? And the statement is initializing a list of the size of somestringarray?
Why can't I just have somestringarray? what is the point of declaring a list of strings, what is wrong having just somestringarray?
Arrays are extremely bare-bones, fundamental components of the Java language, without any of the nice features provided by the collections framework: no contains, fixed-size, unavoidably mutable, and so on.
Arrays.asList returns a special List implementation that is just a wrapper around the array passed to it: it supports set, contains, iteration, and all of that, though it doesn't support add or remove. It can be passed to many utilities that expect a Collection, however, because Arrays.asList does return a List, which is always a Collection.
The statement
List<String> A = new ArrayList<String>(Arrays.asList(somestringarray));
is, first, wrapping your array as a List, but a limited implementation that does not support resizing. (Also, the List reflects changes you make to somestringarray, and changes to the List returned by Arrays.asList would actually change the backing array as well.) Then, it copies that into an ArrayList, which is a full-featured List implementation supporting resizing, etc., and since it makes a copy it is now independent of the original array.
Java Arrays are not dynamic data structures; once intialized they can't be resized. Whereas List is a Collection interface, and ArrayList is a List backed by an array.
List<String> al = new ArrayList<>(Arrays.asList("a", "b"));
al.add("c");
With arrays you'd need
String[] arr = {"a","b"};
// can't add "c" now.
to add "c" when you initialize arr without copying it into a new array,
String[] t = new String[arr.length + 1];
System.arraycopy(arr, 0, t, 0, arr.length);
t[t.length - 1] = "c";
arr = t;

Java - Casting, Generics, Objects and Arrays

I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.

List of Arrays in Java

What is the syntax for making a List of arrays in Java?
I have tried the following:
List<int[]> A = new List<int[]>();
and a lot of other things.
I need to be able to reorder the int arrays, but the elements of the int arrays need not to be changed. If this is not possible, why?
Thank you.
Firstly, you can't do new List(); it is an interface.
To make a list of int Arrays, do something like this :
List<int[]> myList = new ArrayList<int[]>();
P.S. As per the comment, package for List is java.util.List and for ArrayList java.util.ArrayList
List<Integer[]> integerList = new ArrayList<Integer[]>();
Use the object instead of the primitive, unless this is before Java 1.5 as it handles the autoboxing automatically.
As far as the sorting goes:
Collections.sort(integerList); //Sort the entire List
and for each array (probably what you want)
for(Integer[] currentArray : integerList)
{
Arrays.sort(currentArray);
}
List is an interface, not a class. You have to choose what kind of list. In most cases an ArrayList is chosen.
List a = new ArrayList();
You've mentioned that you want to store an int array in it, so you can specify the type that a list contains.
List<int[]> a = new ArrayList<int[]>();
While you can have a collection (such as a list) of "int[]", you cannot have a collection of "int". This is because arrays are objects, but an "int" is a primitive.

Categories

Resources