Not sure about Array size [duplicate] - java

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

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

How to get unique elements from an array and length of resulting array

I have an sorted array consisting elements (1,1,2,3,3,4). I want to get unique elements from this array and length of the resulting array.
Output array should consists (1,2,3,4) and size = 4.
If you are using Java 8, you can do it in the following way:
Arrays.stream(arr).distinct().toArray();
DEMO
The easiest thing to do here might be to just add your array elements to a sorted set, e.g. TreeSet:
int[] array = new int[] {1, 1, 2, 3, 3, 4};
Set<Integer> set = new TreeSet<>();
for (int num : array) {
set.add(num);
}
This option would make good sense if your code also had a need to work with a set later on at some point.
Is this for homework? If it is, please say so. I'm going to assume it is.
I would traverse the array and use a List to store values that I have already seen. If I come across a value that already appears in my List, I'll skip it. If not, I'll add it. Then I'll convert the list to an array and return it. I'm not going to write it for you because I'm assuming it's homework, but that is the basic idea.
NOTE: If performance is a concern, use a HashMap instead of a List.

initializing size of ArrayLIst [duplicate]

This question already has answers here:
Initial size for the ArrayList
(17 answers)
Closed 7 years ago.
How can I initialize the size of an ArrayList? The below code that works for initializing the size of a int array but does not work similarly for ArrayList. It prints 10 for the int array and 0 for the ArrayList. Thank you.
int[] intArray = new int[10];
ArrayList<Integer> arrlist = new ArrayList<Integer>(10);
System.out.println("int array size: " + intArray.length);
System.out.println("ArrayList size: " + arrlist.size());
That is because ArrayLists work differently than standard arrays.
When you pass in 10, you're telling it to allocate space for 10 elements, but since you haven't added anything to the ArrayList yet, size() will return 0.
Try adding an element and then printing the size - that should help you understand how it works. When in doubt, check the docs.
The size that you pass as argument is the initial container size for arraylist. Once you start storing database then only you will get appropriate size for your arraylist. Since the nature of the ArrayList is keep growing/reducing with the data insertion/removal into/from the list.

Adding item to array in java? [duplicate]

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

Find largest (or smallest) element in unordered array in one statement while preserving order [duplicate]

This question already has answers here:
Finding the max/min value in an array of primitives using Java
(16 answers)
Closed 9 years ago.
I know how to find the largest and smallest elements of a Java:
sort the array
use a for loop to iterate over the array and check for the smallest.
But is there a way to check for the largest or smallest in one statement? Also, order needs to be preserved.
Conditions:
No method calls in the same class
Sequence is unsorted, and remains unsorted
No access to external libraries (i.e. ArrayUtils is not allowed).
Assume that this is a plain Java array, i.e. int[], not ArrayList<T> or LinkedList<T>.
Integer arr[] = new Integer[50];
// fill the array with integers
Collections.min(Arrays.asList(arr));
Collections.max(Arrays.asList(arr));
Example:
Integer arr[] = {7, 8, 1, 2, 6};
System.out.println(Collections.min(Arrays.asList(arr)));
System.out.println(Collections.max(Arrays.asList(arr)));
Output:
1
8
If you must use int[] instead of Integer[] with the one statement constraint as proposed, you can make use of ArrayUtils.toObject function which will convert the int[] to it's corresponding wrapper class Integer[]. But i don't think you are after using external library though.

Categories

Resources