Populating ArrayList - java

I am trying to populate an array list, however, my array list constantly equals 0, and never initializes, despite my declaring it over main().
This is my code.
static ArrayList<Integer> array = new ArrayList<Integer>(10); //The parenthesis value changes the size of the array.
static Random randomize = new Random(); //This means do not pass 100 elements.
public static void main (String [] args)
{
int tally = 0;
int randInt = 0;
randInt = randomize.nextInt(100); //Now set the random value.
System.out.println(randInt); //Made when randomizing number didn't work.
System.out.println(array.size() + " : Array size");
for (int i = 0; i < array.size(); i++)
{
randInt = randomize.nextInt(100); //Now set the random value.
array.add(randInt);
tally = tally + array.get(i); //add element to the total in the array.
}
//System.out.println(tally);
}
Can someone tell me what is going on? I feel rather silly, I've done ArrayLists for my default arrays and I cannot figure this out to save my life!

new ArrayList<Integer>(10) creates an ArrayList with initial capacity of 10 but the size is still 0 as there are no elements in it.
ArrayList is backed by an array underneath so it does create an array of a given size (initial capacity) when constructing the object so it doesn't need to resize it every time you insert a new entry (arrays in Java are not dynamic so when you want to insert a new record and the array is full you need to create a new one and move all the items, that's an expensive operation) but even though the array is created ahead of time size() will return 0 until you actually add() something to the list.
That's why this loop:
for (int i = 0; i < array.size(); i++) {
// ...
}
Will not execute as array.size() is 0.
Change it to:
for (int i = 0; i < 10; i++)
And it should work.

Related

creating an array from doubly linked list indexes positions

I have a problem with one of our old exam tasks.
the task is
"the method positions should return a field containing exactly the positions of those elements of the list that have null as content. if there are no such elements than return a field with the length 0"
the code starts with :
public int[] positions() {
int[] result = new int[0];
I keep getting stuck on because of the "new int[0]" when I tried solving the problem without it I managed to get somewhat of a result. but I don't know how to do it with this part.
Just think for a moment what the code is doing here.
int[] result = new int[0];
creates an empty, fixed lenght, primitive array. This array cannot be further expanded.
Your exam task would be translated as (simplifying at a large degree):
public int[] positions(final Object[] objects) {
// Initialize the array with the max possible size, which is the input array size
final int[] positions = new int[objects.lenght];
int j = 0;
for (int i = 0; i < objects.length; i++) {
if (objects[i] == null) {
// Assign the index of the null value to the holder array.
// Increment j, which is the index of the first free position in the holder array
positions[j++] = i;
}
}
// This will return a copy of the "positions" array, truncated at size j
return Array.copyOf(positions, j);
}

Inputting values to a full 2d array

I'm currently trying to figure out how to add values into a full 2d array. Any help would be appreciated.
This is what i currently have.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray)
{
//Creates a new array with an extra row
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++)
{
for (int ii = 0; ii <= newArray[0].length; ii++)
{
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length)
{
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
}
else
{
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
What I currently have done is input a value to the new row however the method is going to be called multiple times to add more than one value. Which mean it's going to create multiple rows rather than adding to the next available column.
EDIT:
mistyped the data type the array and value are suppoed to be objects.
First, your code throws an IndexOutOfBoundsException. Here is why:
Consider the if (i <= oldArray.length) clause. Say, oldArray.length is 3. When i = 3, newArray[i][ii] = oldArray[i][ii] line seeks the oldArray[3][ii] elements but there are no such elements. All the possible elements of oldArray is oldArray[0][ii], oldArray[1][ii] and oldArray[2][ii], since counting starts with 0 in programming.
Second, I didn't get the point of adding another row for each next value. If you're not going to add a set of values to each row, then, why do you consider expanding number of rows?
This is a typical situation when you need to make a tradeoff between element access complexity and complexity of adding new column
If you need fast column adding without new structure allocation you should use LinkedList as a storage of rows and call list.add(row) every time you need to add a new column so your code will look like:
public static void addValue(int value, LinkedList<int[]> list) {
int[] row_you_need_to_add = new int[list.get(0).length];
for (int i = 0; i < list.get(0).length; i++) {
row_you_need_to_add[i] = value;
}
list.add(row_you_need_to_add);
}
As 2D Array is an Array which consist of an array within an Array. So at every index of 2D array there is another array is present and has a specific size.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray) {
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++) {
for (int ii = 0; ii <= newArray[0].length; ii++) {
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length) {
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
} else {
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}

How can I remove a given number of elements from an array?

I have a JLabel array that starts with an integer number of elements. How can I remove an certain number of elements from the array? For example, every time the int is updated:
int i = 21;
i = i - removedElements
How can I update the array to contain that many elements, instead of creating an entirely new array with the desired number of elements?
As others have already mentioned, List is the way to go here since it is specifically designed for adding and or deleting elements.
However if you would prefer to use the JLabel Array you already have in established then you will need to realize that the only way to delete an element from that array is to actually create another array with the desired element to delete excluded from it then return it into the original array. Below I have supplied a simple method named deleteJLabelFromArray() that can do this for you:
public static JLabel[] deleteJLabelFromArray(JLabel[] srcArray, int... indexesToDelete) {
int counter = 0;
JLabel[] newArray = new JLabel[srcArray.length - indexesToDelete.length];
for (int i = 0; i < srcArray.length; i++) {
boolean noGo = false;
for (int j = 0; j < indexesToDelete.length; j++) {
if (i == indexesToDelete[j]) { noGo = true; break; }
}
if (noGo == false) { newArray[counter] = srcArray[i]; counter++; }
}
return newArray;
}
With this method you can delete whatever indexes you supply within the indexesToDelete argument (delimited with a comma). Copy/Paste the code into your project then you can use it something like this:
JLabel[] jla = {jLabel2,jLabel3,jLabel4,jLabel5};
jla = deleteJLabelFromArray(jla, 2);
for (int i = 0; i < jla.length; i++) {
System.out.println(jla[i]);
}
In this example we are going to delete the element number 2 (remember that arrays are 0 based) and therefore jLabel4 would be removed from the Array.
Keep in mind that this would be scary stuff with really big arrays.
Hope this helps.

Random number from an array

I tried to generate a sorted list of random data with no duplicates in descending order for my array. It also returns number of duplicates, but it keeps printing out nothing but zero .... Can anyone help me please :(
// 2. Ask the user for size of arbitrary numbers.
System.out.print("Please enter a size for arbitray numbers: ");
int size = indata.nextInt();
int [] SortedNumbers = new int [size];
// 3. Process arbitrary numbers and remove all duplicates
int numDuplicates = generate_data(SortedNumbers);
// 4. Print the numbers and number of duplicates
printArray(SortedNumbers, numDuplicates);
and here is the random method
public static int generate_data (int [ ] list){
int duplicates = 0;
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
return duplicates;
}
here is the print_array method
public static void printArray(int [] list, int duplicates) {
// Additional code required
System.out.println("\nSize of array: " + list.length + " .Numbers of duplicates: " + duplicates); for (int i = 0; i<list.length; i++){
System.out.printf("%7d", list[i]);
if ((i + 1) % 10 == 0){
System.out.println();
}
}
}
random.nextInt(n.length)
gives you a random index of your array.
But printing the value corresponding to this index, will always give you 0. As you never store any other value in the array.
You should rather do something like this :
int[] list = new int[10];
int duplicates = 0;
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int nextVal = random.nextInt(list.length);
System.out.println("list["+i+"] = "+ nextVal);
// test duplicates
for (int index = 0; index < i; index++) {
if (list[index] == nextVal) {
duplicates++;
break;
}
}
list[i] = nextVal;
}
return duplicates;
Your generate_data method always returns 0, since the local field duplicates is initialized with a 0 value and never changed.
The n field referenced by your generate_data method (which you haven't posted) is likely to be an int[], but its elements might not have been initialized (hence the print out will print default value 0, if within array index).
Hence your numDuplicates local field is always 0 too.
Notes
Your Random initialization is not performing. You should initialize a static Random object in your class and re-use it, instead of re-initializing every time in your generate_data method.
You probably want to have a look at coding conventions for Java in terms of field naming
You might want to post the code in your printArray method as well

How to insert a series of elements in an array?

How to insert a series of elements in an array
The current code to insert one element in an array is as follows:
public static void getArrayElement()
{
try
{
if(initialSize==1)
{
//Get the user input
System.out.print("Enter the element: ");
getElement = key.nextInt();
//Assign the user input to the array
for(int i=0; i<index; i++)
{
array[i] = getElement;
}
}
//If the size of the array is not 1 use this
else
{
//Gets the user input
System.out.print("Enter the element: ");
getElement = key.nextInt();
//Create a new empty array with a new size
int[] temp = new int[index];
//Assign the old array into the new array
for(int j = 0; j < index-1; j++)
{
temp[j] = array[j];
}
//Change the size of the old array
array = new int [index];
//Assign the temporary array into the new array with its new size
for(int aSize = 0; aSize< array.length; aSize++)
{
array[aSize] = temp[aSize];
int k = array.length;
array[k-1] = getElement;
}
//Pass the array into sortArray method for sorting
sortArray(array, index);
}
//Increment the index and initialSize
index++;
initialSize++;
}
catch(InputMismatchException e)
{
System.out.println("Invalid Input");
System.exit(0);
}
}
As you see the above code can insert only one element at a time. But if I want to insert a bunch of elements at a time, How do i do that ?
Before finding an answer it is better to understand what arrays are.
Array is a set a of homogeneous elements stored in a contiguous memory
location.
This makes a limitation that Arrays need to know the size when they are initialized to reserve enough space from the memory. This makes insertion not possible at all in the parent array. For that you will have to do an arraycopy or create a new array with a different size.
For example,
int[] array = new int[10]; //Initializes an integer array of size 10.
for(int i=0;i<10;i++){
array[i] = i;
}//stores values from 0 to 9.
Now if you intend to insert one or 'n' elements at the start, you have to either create a new array with size "size of prev array + 1" or "size of prev array + n" respectively. And perform an array copy followed by an insertion at the start.
So, if you want a dynamic object doing this for you (inserting one, inserting in bulk), you will have to define your custom capacity that the array can hold. And then you will have to increase the capacity based on your preference.
Developing on this problem, you will reinvent the Java's ArrayList. So better use it in your case.
If key is a Scanner you could just do this:
while( key.hasNextInt() ) {
int i = key.nextInt();
//do with i whatever you want
}
I'd also suggest using a list instead of an array. Then just pass the list to Collections.sort(list) to keep it sorted.
Although lists only allow you to add objects you could make use of autoboxing and convert an int to Integer upon inserting.
Alternatively there are libraries that support primitive lists out there - Google Guava and Apache Commons, for example, should provide some.
Another alternative might be sorted collections like Apache Common's TreeBag which allows you to add multiple duplicate items into a sorted structure.
You want to copy content of temp into array. You can achieve this in one at most two steps
if (temp.length > array.length)
array = new int[temp.length];
System.arraycopy(temp, 0, array, 0, temp.length) ;

Categories

Resources