Adding item to array in java? [duplicate] - java

This question already has answers here:
How to add new elements to an array?
(19 answers)
How can I dynamically add items to a Java array?
(11 answers)
Closed 8 years ago.
I have an array, defined as below:
String[] letters = {"ab", "cd", "ef", "gh"};
How would I go about adding an item to this array?

1.Arrays are fixed in size
2.Before declaring an array we should know the size in advance.
3.We cannot add anything dynamically to an array once we declare its size.
I recommend you to go for collection framework like List or Set where you can increase the size dynamically

By using this type of array initialization you cannot simply add more elements.
String[] letters = {"ab", "cd", "ef", "gh"};
Could be paraphrased as:
String[] letters = new String[4];
letters[0] = "ab";
letters[1] = "cd";
letters[2] = "ef";
letters[3] = "gh";
So, your array's length is only 4.
To add more elements you should somehow copy you array to a bigger one and add elements there. Or just use ArrayList which does the hard work for you when capacity is exceeded.

Java arrays having static size. One you define the size of a array, it can't grow further dynamically.
Your letters array has a size of 4 element. So, you can't add more element to it.
Use ArrayList instead
List<String> letters = new ArrayList(); // Java 7 and upper versions
letters.add("ab");
letters.add("cd");
....// You can add more elements here

This is not possible without a workaround
like http://www.mkyong.com/java/java-append-values-into-an-object-array/
try ArrayList, List, Map, HashMap or something like this instead

Related

Is it possible to have a 2D array as member attribute but not initialized in constructor?

Problem is I have a text file I need to read that contains chars and I need to construct that into an 2D array internally in a class. But since when I initialize I also have to specify the values like so:
int[] array;
array = new int[] {2, 7, 9};
Since I don't know the size of the array before I read the file, I am able to create one as a member, but as a local one only. As of this, I resorted to using arrayLists, which is not desirable. Am I missing something?
Thanks.
ArrayList would be the best option for this problem because the size of the ArrayList is mutable, meaning that no matter the size of the data, it will always change it's size to match the amount of elements it contains.
Here's more detail on creating and using 2D ArrayLists.
Hope this helps.
List<Integer> array = new ArrayList<>();
array.add(2);
array.add(7);
array.add(9);
OR prior to Java 9:
List<Integer> array = new ArrayList<Integer>(Arrays.asList(2,7,9));
array.add(10);
OR in Java 9:
List<Integer> array = List.of(2,7,9);

Taking a random percentage of a vector in Java [duplicate]

This question already has answers here:
Take n random elements from a List<E>?
(12 answers)
Closed 8 years ago.
I am using Java and I am using a vector 'set' to store data
This is created from a text file as I read each line and store it in an array values[]. Then I have a vector 'set' and for each line I add values[] to the vector 'set' so set looks as shown as above after all the data from the text file is read.
Then the user is given a choice to input the amount of data he wants, for example if he enters 50, half of the vector (the first 7 lines) would be taken by using:
public void pro(int percentage)
{
int noOfEx = percentage*set.size()/100;
root.keptEx = new Vector(set.subList(0, noOfEx));
}
However, I wish that the lines are taken randomly and not after each other but I cannot figure out how to do it with random. Also is there a way how to print out the values of the vector? since
System.out.println(keptEx)
displays weird symbols not the actual contents.
Shuffle the list of rows:
Collections.shuffle(list);
Then take the first N rows of the shuffled list. Note that calling set what is in fact a list is not a very good idea. Also note that Vector shouldn't be used anymore since Java 2, and we're at Java 8. Use an ArrayList instead. And use generic types, not raw types. These exist since Java 5.
The easiest way to print your list would be to make it contain lists instead of arrays (i.e. you would jave a List<List<Integer>> instead of a List<int[]> (assuming that's what you have). If you want to keep using arrays, then you'll have to loop over each element of your list:
for (int[] row : list) {
System.out.println(Arrays.toString(row));
}

Not sure about Array size [duplicate]

This question already has answers here:
Java dynamic array sizes?
(19 answers)
Closed 8 years ago.
How may I define an array in Java. when I am not sure of the Arrays size.
I am doing it to avoid Null Pointers
int[] arr1 = new int[21];
int[] arr1 = {11,22,33};
These are of fixed length, i need to declare an Array where the items to be stored in it will be decided at run time?
You could use an ArrayList, which dynamically grows/shrinks according to how many elements you place/remove in it.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
if you are not sure just declare it like this:
int[] arr1;
but you must know its size when you initialise it later:
arr1 = int[20];
//or
arr1 = {1, 2, 3};
On the other hand this is the situation where you should use List (like ArrayList) since they resize dynamically.
EDIT:
List<Integer> list = new ArrayList<Integer>();
//adding
list.add(2);
more methods here: http://docs.oracle.com/javase/7/docs/api/java/util/List.html
"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."
ArrayList Tutorial

java Converting a set to an array [duplicate]

This question already has answers here:
How to convert Set<String> to String[]?
(7 answers)
Closed 4 years ago.
I'm trying to convert my set of Strings to an array of Strings so I can operate on them one by one. Is there a better way of doing this or is converting to arrays a good way? However, when I try converting to an array like below then I get errors as it doesn't think that it will always be strings passed in. Would appreciate some pointers.
Set<String> s;
s.add("a");
s.add("b");
String[] item = s.toArray();
You do not have to convert a Set to an array just to operate on the elements. You can iterate over the elements directly
Set<String> s = new HashSet<>();
....
for (String item : s)
{
do something...
}
so I can operate on them one by one
You don't have to convert it to an array for that.
Instead iterate using the for-each loop or the iterator.
you can do something like this
String[] item = s.toArray(new String[s.size()]);
As per Java doc - toArray function ( which is the one you need )
toArray() Returns an array containing all of the elements in this list
in proper sequence (from first to last element).

How can I select random element from the list? [duplicate]

This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 4 years ago.
I am using java.util.LinkedList
Is there any method that helps me with this?
int len = list.size();
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(len);
If you only need one element you can use the Random class to generate a (pseudo) random value (as you wrote in your question):
E element = list.get(new Random().nextInt(list.size()));
Remember LinkedList.get(index) is an O(n) operation, as noted in the comments it's better to use an ArrayList for this purpose.
If you want to shuffle the whole array you can use the Collections api like this:
Collections.shuffle(list);
You can also shuffle the List using Collections.shuffle and pick the first element everytime though this might be a bit expensive computation wise. Just another trick you should be aware of. :-)
final List<String> lst = Arrays.asList("a", "b", "c");
Collections.shuffle(lst);
final String rndStr = lst.get(0);
Get the list length with size(), create a random number between 0 and size-1 and use get(index) to retrieve the element with that index.
If you really need just one element, go with dacwe's solution. If you need several values (e.g. when simulating a card game, bingo etc.) you can use java.util.Collections.shuffle(list);, and call list.remove(0); for every element you need.

Categories

Resources