I want to add a String to a specific location in an ArrayList that looks like this:
ArrayList <String[][]> arrayList3D = new ArrayList<>(Arrays.asList(arrayString3D));
I tried this out:
arrayList3D.get(0).get(1).add("new Word");
but it didn't work...
Man, first you should create an array and later the another. try this.
ArrayList<ArrayList<String>> arrayList3D = new ArrayList<ArrayList<String>>();
Later, you should create the another.
arrayList3D.add(0, new ArrayList<String>());
but you show that you want to do this.
arrayList3D.get(0).get(1).add("new Word");
The problem here is that does it exist a value in that position. It does, it works, but, it doesn't.. you should write this.
ArrayList3D.get(0).add(1, "value to input");
You're close but not quite correct.
The process goes as follows:
arrayList3D.get(0) regardless of the index provided ( 0 or greater) will return a 2D array i.e String[][].
so in order to access a particular position of the 2D array, you'll need to use 2 pairs of square brackets one indicating the row and another indicating the column.
i.e
arrayList3D.get(0)[1][0] = "new Word";
Arrays in Java don't provide get methods. An equivalent is given by bracket notation. You set the element at index i like:
array[i] = value;
Your ArrayList contains elements of type String[][] which are arrays that contain other arrays that hold String elements.
So a correct access would look like:
arrayList3D.get(0)[1][i] = "new Word";
Where i is the position you want to add the element in the last array.
Maybe this view helps more:
arrayList3D // ArrayList<String[][]>
.get(0) // String[][]
[1] // String[]
[i] // String
= "new Word";
If you want to have get methods and be able to dynamically add elements, you would need something like ArrayList<List<List<String>>> instead since arrays are of fixed size.
You could do it by manually converting your String[][][] to List<List<List<String>>>, for example by using regular loops:
List<List<List<String>>> arrayList3D = new ArrayList<>();
// Traverse all 2-dim elements
for (String[][] dim2Arr : arrayString3D) {
List<List<String>> arrayList2D = new ArrayList<>();
// Traverse all 1-dim elements
for (String[] dim1Arr : dim2Arr) {
List<String> arrayList1D = Arrays.asList(dim1Arr);
// Add 1-dim to 2-dim
arrayList2D.add(arrayList1D);
}
// Add 2-dim to 3-dim
arrayList3D.add(arrayList2D);
}
Related
I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.
In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.
for(int i=0;i<lines.size();i++){
String[] splitting = lines.get(i).split("\t");
}
You could use Scanner to specify delimiter as tab..and use dynamic array i.e. ArrayList for adding columns.
BufferedReader reader= new BufferedReader(new FileReader("D:/sagar.txt"));
Scanner sc= new Scanner(reader);
sc.useDelimiter("\\s+"); // regex for specifying one or more tabs
List<String> a=new ArrayList<String>();
List<String> b =new ArrayList<String>();
while((sc.hasNextLine())){
a.add(sc.next());
b.add(sc.next());
}
System.out.println("First Column");
for (String string : a) {
System.out.println(string);
}
System.out.println("Second Column");
for (String string : b) {
System.out.println(string);
sagar.txt
hi ssup
hello gm
Create two more arrays.
Put this after your split.
array1[i] = splitting[0];
array2[i] = splitting[1];`
You need to set the size of the two new arrays to lines.size(). I would use List instead of Array.
So I initialized an array lets say
`string example = new string [5];
When I called the split method on a line of
string x = "abc, def, g";
example = x.split(",");
example[0] = abc
example[1] = def
example[2] = g
I can no longer access example[3] and example[4] as I am getting null pointer
shouldn't these still be accessible with values of null?
Even though you created a array with some initial length for example
String [] sample = new String[5];
after assigning new Array to the variable It will create a new array with new array size. for example.
String s = "Hi how are you";
sample = s.split(" ");
so you can not access old array elements.
It doesnt preserve the values. "example" is assigned with a completely new and different array.
If you want to preserve the number of elements previously present in the array, you can do something like:
int num = example.length;
example = x.split(",");
example = Arrays.copyOf(example, num);
// initialize the new array elements here.
Of course doing so is not very efficent and should be avoided. I suggest you take a look at array lists instead.
Your initial example array (of length 5 with null values) gets overwritten by the new array returned by the call to the split() method, in this case an array of length 3. The initial array referenced by the example reference is not accessible anymore, it will be garbage collected.
If you want to keep both arrays you can assign the result of the split to another variable
String[] example2 = x.split(",");
Hi I'm trying to create a contacts list I have an array of contacts and I'm looping through each one and getting the first character of the last name. I'm then trying to create an array with the value of that character and add it to my final array. Then I want to check if the array already exists in my final array. If it doesn't add it to the array.
The aim being so I end up with an array list of arrays that are going to be headers in a list view. Does anyone know how to create an empty array and name it the value of a string (I'm going to add stuff to this array later)? and then add that to an array list?
Here is what I have tried so far but I'm struggling to get my head round it
for (int i=0; i<contactsJSONArray.length(); i++) {
singleContactDict = contactsJSONArray.getJSONObject(i);
Log.v("Main", "Contact singleContactDict " + i +"= " + singleContactDict);
String firstname = singleContactDict.getString("first_name");
String lastname = singleContactDict.getString("last_name");
char firstLetterInLastname = lastname.charAt(0);
Log.v("Main", "firstLetterInLastname = " + firstLetterInLastname);
headerWithLetterArray.add((firstLetterInLastname).toArray);
}
array is something like [a,b,c,d], they don't have names. If you mean JSONArray and you want to store everything is JSONObcject try:
parentJson.put(lastname.substring(0,1), new JSONArray());
You can try using "Map" for the final collection. Where your first character of the last name can be a key in the map and the real name will become value (value internally can be a arraylist).
When you want to add a new contact to list, you can first look for the key in the map with the first letter. If it is then get the value which is arraylist and add the new contact to that.
In this way you will have lots of arraylist marked by the single letter in map which can be used in loop to fill the list.
Does anyone know why this doesn't compile?
public class ArrayCompare{
public static void main (String []args){
String words= "Hello this is a test";
String delimiter=" ";
String [] blocker=words.split(delimiter);
String [][] grid= new String [100][100];
grid[0]="Hello";
if (grid[0].equals(blocker[0])){
System.out.print("Done!");
}
}
}
I would like to perform this function of comparison using a 2 dimensional array. I am a newbie! Please help if you can. Thanks in advance!
Try this:
grid[0][0]="Hello";
grid is a two-dimensional array. For the same reason, you need to do this:
if (grid[0][0].equals(blocker[0]))
grid[0] is a String[] type, not a String. So your code should be like this
grid[0] = new String[100];
grid[0][0] = "Hello";
if (grid[0][0].equals(bloker[0])) {
//your logic...
}
String [][] grid= new String [100][100];
grid[0]="Hello";
There's your problem. You are trying to assign a string to a string array. Think of a 2d array as an array of arrays.
You probably want something like
grid[0][0]="Hello!";
grid is 2d array. you can't do like d[0] = "Hello". So, if you want to assign value at 0 position
d[0][0] = "Hello";
if (grid[0][0].equals(blocker[0])){
System.out.print("Done!");
}
It won't compile because grid[0] is not String type.
It is String[] (Array) type. Variable grid[0] is actually pointing to a String[100] array.
You are attempting to assign a string "Hello" to an array by
grid[0]="Hello"; statement.
If you want to assign a string to a location in grid, you must provide two index(s) - following is legal:
grid[0][0]="Hello";
May I suggest using eclipse or BlueJ to edit your Java code? so that such basic errors are shown on real-time and explained well?
First thing you can't assign value to the element of the multi dimensional array using single index
grid[0]="Hello";
you need to specify both the indices like grid[0][0] = "Hello"
this will set the 0th element of 0th row to Hello
Likewise while compairing
if (grid[0].equals(blocker[0])){
System.out.print("Done!");
you have to pass the same indices here (You cannot compare a String to a Array Object)
if (grid[0][0].equals(blocker[0])){
System.out.print("Done!");
I'm looking to create an array that will be able to change size over time because the size of the array is unpredictable and I don't want to create a huge random number that will waste memory so every time a button is pressed I need the array to grow by one.
private String[][] lyricLineInfo = new String[x][5];
In the place of x is where the array must grow upon the button push and 5 is a constant. So I need the x button to grow by one without overflowing. Can I do it by using something like this?
lyricLineInfo[lyricLineInfo.length + 1][4] = fieldLyrics.getText();
Anyways thanks in advance!
Use an ArrayList<String[]> (see the docs here). It will grow automatically. (It uses an internal array that doesn't actually grow by just 1 when it needs to grow. Since growing is an expensive operation, it grows by some larger amount so it can absorb a few more items before having to grow again.)
EDIT
For example, here's how you could recode the two lines of your original post:
private ArrayList<String[]> lyricLineInfo = new ArrayList<String[]>();
lyricLineInfo.add(fieldLyrics.getText());
The second line assumes that fieldLyrics.getText() returns a String[]. If I misunderstood your intent and it returns a String, then you could do the following:
String[] nextStrings = new String[5];
nextStrings[4] = fieldLyrics.getText();
lyricLineInfo.add(nextStrings);
If the second index isn't always 5 long, you can also have an ArrayList of ArrayLists:
private ArrayList<ArrayList<String>> lyricLineInfo
= new ArrayList<ArrayList<String>>();
Then you could lyricLineInfo.add(new ArrayList<String>()); to extend the array.
EDIT 2
#clankfan1 - In your comment, you asked how to do a particular operation. Let's say we're using the ArrayList<ArrayList<String>> structure. It would go something like this:
ArrayList<ArrayList<String>> lyricLineInfo = new ArrayList<ArrayList<String>>();
ArrayList<String> line = new ArrayList<String>();
line.add("true");
line.add("true");
line.add("0.0");
line.add("5.0");
line.add("First Line");
lyricLineInfo.add(line);
line = new ArrayList<String>(); // don't use clear(): need a new object here
line.add("false");
line.add("false");
line.add("5.0");
line.add("10.0");
line.add("Second Line");
lyricLineInfo.add(line);
String secondLineTitle = lyricLineInfo.get(1).get(4); // will be "Second Line"
Obviously, this logic is amenable to being put into a separate method.
EDIT 3
If you need the elements of lyricLineInfo to be of type String[], it is vital that each element be a distinct array. Here are a few coding styles for adding elements:
ArrayList<String[]> lyricLineInfo = new ArrayList<String[]>();
String[] line = { "true", "true", "0.0", "5.0", "First Line" };
lyricLineInfo.add(line);
// now for a second style:
line = new String[5];
line[0] = "false";
line[1] = "false";
line[2] = "5.0";
line[3] = "10.0";
line[4] = "Second Line";
lyricLineInfo.add(line);
// and a third style:
lyricLineInfo.add(new String[] {
"false", "true", "10.0", "15.0", "Third Line"
});
String secondLineTitle = lyricLineInfo.get(1)[4]; // will be "Second Line"
You could use java.util.Vector<String[]>.
Use an ArrayList like this:
private ArrayList<ArrayList<String>> lyricLineInfo = new ArrayList<ArrayList<String>>();
ArrayLists are flexible arrays in java. When you want to add something do this:
lyricLineInfo.add(stringToBeAdded, index) //for the first dimension and
lyricLineInfo.get(firstIndex).add(stringToBeAdded, index); //for the second dimension
Use a List instead:
private List<String[]> lyricLineInfo = new ArrayList<String[]>();
Then to add to the list you use:
lyricLineInfo.add(new String[5]);
and to get you do:
// Get the 3rd element (array index 2).
String[] strings = lyricLineInfo.get(2);
Why don't you think about using Collections if you need an array with undefined size? :)
You can't do that with an array, but you can use a List object. You could try something like this:
private List<String[]> lyricLineInfo = new ArrayList<String[]>();
So then, assuming fieldLyrics.getText() returns a String[], you would do:
lyricLineInfo.add(fieldLyrics.getText());
If you only add new elements and iterate over all elements in list you should use LinkedList instead.
Collections are heavily used in Java. You should check Java Collections Framework - tutorial