Java - Creating an Undefined Array - java

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

Related

How to add Element to 3 dimensional ArrayList? - Java

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

java: does the string .split method change the size of an 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(",");

Store a text lines in an array in java

I have some texts which contain some lines. There is a word in every line. I should copy the text and then paste it to the Eclipse Console Output window and finally store each line in an array.
I don't know how many lines does each text have. How could I do this?
I know if I want to store some strings to an array I should do like bellow, but I don't want to do by this method:
String[] Lines = {"line1", "line2", ....};
If you don't know how many lines you will have you could use a generic list.
List<String> lines = new ArrayList<String>();
This will resize dynamically as you add values to it.
You could also use arrays and do the resizing yourself, which is what the ArrayList does behind the scenes, it's just that it adds complexity to your code.
You can not change an array size after you initialize it. If you change your previous data will be lost. You can use ArrayList to add items dynamically. For example;
ArrayList<String> list = new ArrayList<>();
//read your file here and print it. After that;
list.add(line); // I assumed you get lines to a variable called line
If you are using JDk 7+ you could easily do this by
List<String> list = Files.readAllLines(new File("test.txt").toPath());
But if you still want to use array convert that list to array like
List<String> list = Files.readAllLines(new File("test.txt").toPath());
String[] str = list.toArray(new String[list.size()]);
Or if you dont have a file and copy pasting to console try this
List<String> lines = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while(s.hasNextLine()){
String line = s.nextLine();
if(line.length() > 0) {
lines.add(s.nextLine());
} else {
break;
}
}
System.out.println(lines);

Read a file and convert it to an array (Java)

So I have a collection of phrases that are separated by newlines and I would like to populate an array with these phrases. This is what I have so far:
Scanner s;
s = new Scanner(new BufferedReader(new FileReader("Phrases.txt")));
for(i = 0; i < array.length;i++)
{
s.nextLine() = array[i];
}
Is there a fast and simple way to just populate an array with phrases separated by newlines?
The assignment should be reverse: -
array[i] = s.nextLine();
And, I think you should fill your array based on the input received from the file. Here you are receving input based on the length of your pre-declared array. I mean, since you are using an array, your size is fixed. So you can only populate it with a fixed number of phrases.
A better way would be to use an ArrayList.
List<String> phrases = new ArrayList<String>();
Now, you can populate your arraylist, based on the phrases you get from your file. You don't need to pre-define the size. It increases in size dynamically.
And to add phrases, you would do: -
phrases.add(s.nextLine());
With a while loop to read till EOF.
while (s.hasNextLine()) {
phrases.add(s.nextLine());
}
Since you don't know how many phrases you're likely to have (I suspect), I would populate an ArrayList<String> and convert it to an array using ArrayList.toArray() once you're done. I'd perhaps keep it as a Java collection, however, for greater flexibility.
You have the assignment operation inverted (array[i] should be set to s.nextLine(), not the other way around. Also, it would be best to modify the for loop to terminate when no more lines exist:
for(i = 0; i < array.length && s.hasNextLine() ;i++) {
array[i] = s.nextLine()
}
It can be done with a 1 liner with apache commons and specifically FileUtils.readLines()
FileUtils.readLines(myFile).toArray(new String[0]);
Don't waste your time with Scanner. BufferedReader is just fine. Try this:
BufferedReader br = new BufferedReader(new FileReader("Phrases.txt")));
LinkedList<String> phrases = new LinkedList<String>();
while(br.ready()) {
phrases.add(br.readLine());
}
String[] phraseArray = phrases.toArray(new String[0]);
By the way it's important to use LinkedList not ArrayList if the file is large. That way you only create one array at the end. Otherwise you will have a lot of large array creation and wasted memory.
you are doing it wrong. it has to be
for(i = 0; i < array.length;i++)
{
array[i]=s.nextLine();
}
array[i] = value; // the value would be assigned into the array at index i.
However, a better option would be to use a List implementing classes such as ArrayList which gives you an advantage of dynamic size.
List<String> list = new ArrayList<>();
list.add(s.nextLine(());

Java String formation for ListView

I have created a Java code for my Android App.
String[] MovieName=new String[]{};
for (int i = 0; i < 15; i++)
{
MovieName[i]=movieAtt.getAttributeValue( "name" ); //Value coming from my XML
}
ListViewObject.setAdapter(new ArrayAdapter<String>(screen2.this,android.R.layout.simple_list_item_1 , MovieName));
This code throws an Exception.
I think i am not inserting vaues properly inside Java String Array.
All i want is to have a variable like MovieName={"1","2", "3"} to feed into the ListView of my code.
This is not much helpful too :
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
You initialize an empty array.
Try this
String[] MovieName = new String[15];
Your initilizing an empty string array. That will give you an ArrayOutOfBoundException.
If you always have 15 entries you could initialize it to 15.
String[] MovieName=new String[15];
Otherwise you could create an ArrayList and convert it to an array after you filled it.
If number of elements in MovieName is constant, then you should initialise it as
String[] MovieName=new String[15];
Your current initialisation is equal to
String[] MovieName=new String[0];

Categories

Resources