Is there a way to make it so that, by deleting one object from one ArrayList, it deletes it from all the other ArrayLists that it exists in?
So for example in the code below, if I deleted everything from the ArrayList fives, the ArrayList test1 would contain no NumHolders that contained the value 5.
public static void main(String[] args) throws FileNotFoundException{
ArrayList<NumHolder> test1 = new ArrayList<NumHolder>();
ArrayList<Five> fives = new ArrayList<Five>();
String all = null;
for (int i = 0; i < 90; i++){
NumHolder number = new NumHolder(i);
test1.add(number);
if(i%5==0){
fives.add(number);
}
for (int j = 0; j < fives.size();j++){
fives.remove(0);
}
for (int j = 0; j < test1.size();j++){
test1.get(j).toString();
}
}
its easier than that my friend, just don't add the number numbers that divides on 5 without a reminder to your test1 ArrayList.
ArrayList<NumHolder> test1 = new ArrayList<NumHolder>();
ArrayList<Five> fives = new ArrayList<Five>();
String all = null;
for (int i = 0; i < 90; i++){
NumHolder number = new NumHolder(i);
if(i%5==0){
fives.add(number);
continue;
}
test1.add(number);
}
for (int j = 0; j < fives.size();j++){
fives.remove(0);
}
for (int j = 0; j < test1.size();j++){
test1.get(j).toString();
}
If you want to remove all 5s from both lists just use:
test1.removeAll(fives);
fives.clear();
One thing you could do is, instead of removing your elements from fives, keep them in that list and use the list in a single call on all the other lists:
test1.removeAll(fives);
If you don't want that - if there are too many lists and you don't want to call removeAll() on each list, and you really want all lists to share the elements, then you could wrap the elements in a class that contains a single member variable. Then set the member variable in the wrapper to null, instead of deleting it. Then all lists will be referring to the same wrapper element whose contained value was set to null.
Related
I am using below program to find the subsequences in an given given list. When I am using clear() , the values in li is also getting cleared. Hence, I am creating a new reference everytime.
I wanted to understand the logic behind this. Am I using it wrong? Or it is the reference that I am adding to my li?
public static int getTheSubseq(List<Integer> AList){
// int[][] subsequences = new int[][];
List<List<Integer>> li = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
temp = new ArrayList<>();
//temp.clear();
}
}
System.out.println(li);
return 1;
}
Regardless of whether or not you are calling temp.clear(), if you add to li multiple times a reference to the same List object, li will contain multiple references to the same List object, which means li.get(0) == li.get(1), li.get(0) == li.get(2), and so on...
Making changes in one of these inner Lists will be reflected in all the other inner Lists, since there's just one List referenced multiple times.
Therefore, assigning a new ArrayList instance to temp in each iteration of your loop (before adding it to li) is the right thing to do.
I'd make a slight change though - create the new inner List just before adding it to the outer List:
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
List<Integer> temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
}
}
Adding the element to li doesn't make a copy. So when you call clear() you'll have both temp and an element inside li that point to the same object.
You may want to just declare temp inside the inner loop, so you get a fresh one every time without needing to call clear().
When you call .clear() (or any other method for that matter), you're operating on the same refernece.
Here, if you don't create a new list each iteration, you're adding the list referenced to by temp to li. When you call clear(), they are "all" cleared, since they all point to the same object.
When you create a new list each iteration, you have different objects, and can operate on them independently.
Try doing this:
public static int getTheSubseq(List<Integer> AList){
// int[][] subsequences = new int[][];
List<List<Integer>> li = new ArrayList<>();
List<Integer> temp;
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
}
}
System.out.println(li);
return 1;
}
Could anyone help me and point out what is wrong here? All the fields are non-static. Function shuffle returns each time different array.
List<Point[]> someArray = new ArrayList<Point[]>();
for(int i = 0; i < 4; i++) {
Point[] temporary = new Point[50];
temporary = shuffle(pointsArray.getPoints());
someArray.add(temporary);
print(someArray.get(i));
}
The result of print in the first loop is ok since they're different. Right after getting out of the loop, I want to print elements of list someArray again.
for(int i = 0; i < 4; i++) {
print(someArray.get(i));
}
The result here is 4 time of the last element.
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.
I am trying to use 2D arrayLists in Java.
I have the definition:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
How can I loop through it and enter in numbers starting from 1?
I know that I can access a specific index by using:
myList.get(i).get(j)
Which will get the value. But how do I add to the Matrix?
Thanks
You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList
for (int i = 0; i < myList.size(); i++)
{
for (int j = 0; j < myList.get(i).size(); j++)
{
// do stuff
}
}
Edit: you then fill it by replacing // do stuff with
myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list
A Note: If the myList is initially unfilled, looping using .size() will not work as you cannot use .get(SOME_INDEX) on an ArrayList containing no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE) to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answer for a perfect example.
Use for-each loop, if you are using Java prior 1.5 version.
for(ArrayList<Integer> row : myList) {
for(Integer intValue : row) {
// access "row" for inside arraylist or "intValue" for integer value.
}
}
Assuming the matrix is not initialized,
int m = 10, n = 10;
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < m; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
row.add(j);
}
matrix.add(row);
}
Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve