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

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.

Related

Can i declare an Array once and through out the code declare it again?

Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.

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

A Sorted Integer List

So the original code is
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
and
// ***************************************************************
// ListTest.java
//
// A simple test program that creates an IntList, puts some
// ints in it, and prints the list.
//
// ***************************************************************
import java.util.Scanner ;
public class ListTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
IntList myList = new IntList(10);
int count = 0;
int num;
while (count < 10) {
System.out.println("Please enter a number, enter 0 to quit:");
num = scan.nextInt();
if (num != 0) {
myList.add(num);
count++;
} else {
break;
}
}
System.out.println(myList);
}
}
I need to change the add method to sort from lowest to highest. This is what I tried doing.
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
for (in i = 0; i < list.length; i++) {
}
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
The outcome is very wrong. Any one able to steer me in the right direction? I can sort of see why what I have doesn't work, but I can't see enough to fix it.
So I realize I was not very descriptive here the first time. With the exception of the add method modifications the code was not my doing. My assignment is to only touch the add method to sort the array to print out smallest to largest. This is a beginners class and we do little to no practice my only tools for this are some basic understandings of loops and arrays.
I tried redoing it again and came up with this:
if(list[numElements-1] > value){
for(int i=0; i<numElements; i++){
if(list[i]>value){
for(int j = numElements; j>i; j-- ){
list[j] = list[j-1];
}
list[i] = value;
break;
}
}
numElements++;
}
else
{
list[numElements] = value;
numElements++;
}
my input was:8,6,5,4,3,7,1,2,9,10
the output was: 1,10,1,9,10,1,1,2,9,10
this thing is kicking my butt. I understand I want to check the input number to the array and move all numbers higher than it up one space and enter it behind those so it is sorted on entry, but doing so is proving difficult for me. I apologize if my code on here is hard to follow formatting is a little odd on here for me and time only allows for me to do my best. I think break is not breaking the for loop with i like i thought it would. Maybe that is the problem.
The biggest bug I see is using list.length in your for loop,
for(int i = 0; i <list.length; i++)
you have numElements. Also, I think it's i that needs to stop one before like,
for(int i = 0; i < numElements - 1; i++)
and then
for (int j = numElements; j > i; j--)
There are two lines that have to be moved out of the inner loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
// list[i] = value;
// break;
}
list[i] = value;
break:
}
}
In particular, the inner break means that the loop that is supposed to move all larger elements away to make room for the new value only runs once.
You might want to include Java.util.Arrays which has its own sort function:
http://www.tutorialspoint.com/java/util/arrays_sort_int.htm
Then you can do:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
}
else {
list[numElements] = value;
numElements++;
Arrays.sort(list);
//Or: Java.util.Arrays.sort(list);
}
}
As Eliott remarked, you are getting confused between list.length (the capacity of your list) and numElements (the current size of your list). Also, though, you do not need to completely sort the list on each addition if you simply make sure to insert each new element into the correct position in the first place. You can rely on the rest of the list already to be sorted. Here's a simple and fast way to do that:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
int insertionPoint = Arrays.binarySearch(list, 0, numElements);
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
}
System.arrayCopy(list, insertionPoint, list, insertionPoint + 1,
numElements - insertionPoint);
list[insertionPoint] = value;
numElements += 1;
}
}
That will perform better (though you may not care for this assignment), and it is much easier to see what's going on, at least for me.
Here are some hints.
First, numElements indicates how many elements are currently in the list. It's best if you change it only after you have finished adding your item, like the original method did. Otherwise it may confuse you into thinking you have more elements than you really do at the moment.
There is really no need for a nested loop to do proper adding. The logic you should be following is this:
I know everything already in the list is sorted.
If my number is bigger then the biggest number (which is the one indexed by numElements-1, because the list is sorted) then I can just add my number to the next available cell in the array (indexed by numElements) and then update numElements and I'm done.
If not, I need to start from the last element in the array (careful, don't look at the length of the array. The last element is indexed by numElements-1!), going down, and move each number one cell to the right. When I hit a cell that's lower than my number, I stop.
Moving all the high numbers one cell to the right caused one cell to become "empty". This is where I'm going to put my number. Update numElements, and done.
Suppose you want to add the number 7 to this array:
┌─┬──┬──┬─┬─┐
│3│14│92│-│-│
└─┴──┴──┴─┴─┘
⬆︎ Last element
You move everything starting from the last element (92) to the right. You stop at the 3 because it's not bigger than 7.
┌─┬─┬──┬──┬─┐
│3│-│14│92│-│
└─┴─┴──┴──┴─┘
(The second element will probably still contain 14, but you're going to change that in the next step so it doesn't matter. I just put a - there to indicate it's now free for you to enter your number)
┌─┬─┬──┬──┬─┐
│3│7│14│92│-│
└─┴─┴──┴──┴─┘
⬆︎ Updated last element
This requires just one loop, without nesting. Be careful and remember that the array starts from 0, so you have to make sure not to get an ArrayIndexOutOfBoundsException if your number happens to be lower than the lowest one.
One problem I spotted is that: you are trying to insert the newly added number into the array. However your loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
is always looped through the total length of the array, which is always 10 in your test, rather than the actual length of the array, i.e. how many numbers are actually in the array.
For example, when you add the first element, it still loops through all 10 elements of the array, although the last 9 slots does not have value and are automatically assigned zero.
This caused your if statement always returns true:
if (list[i] > value)
if you have to write the sort algorithm yourself, use one of the commonly used sorting algorithm, which can be found in Wikipedia.
If any one was curious I finally worked it out. Thank you to everyone who replied. This is what i ended up with.
public void add(int value)
{
if(numElements == 0){
list[numElements] = value;
numElements++;
}
else{
list[numElements] = value;
for(int check = 0; check < numElements; check++){
if(list[check] > value){
for(int swap = numElements; swap> check; swap--){
list[swap] = list[swap-1];
}
list[check] = value;
break;
}
}
numElements++;
}
}
so my original is the same but we have to make another class
A Sorted Integer List
File IntList.java contains code for an integer list class. Save it to your project and study it; notice that the only things you can do are create a list of a fixed size and add an element to a list. If the list is already full, a message will be printed. File ListTest.java contains code for a class that creates an IntList, puts some values in it, and prints it. Save this to your folder and compile and run it to see how it works.
Now write a class SortedIntList that extends IntList. SortedIntList should be just like IntList except that its elements should always be in sorted order from smallest to largest. This means that when an element is inserted into a SortedIntList it should be put into its sorted place, not just at the end of the array. To do this you’ll need to do two things when you add a new element:
Walk down the array until you find the place where the new element should go. Since the list is already sorted you can just keep looking at elements until you find one that is at least as big as the one to be inserted.
Move down every element that will go after the new element, that is, everything from the one you stop on to the end. This creates a slot in which you can put the new element. Be careful about the order in which you move them or you’ll overwrite your data!
Now you can insert the new element in the location you originally stopped on.
All of this will go into your add method, which will override the add method for the IntList class. (Be sure to also check to see if you need to expand the array, just as in the IntList add() method.) What other methods, if any, do you need to override?
To test your class, modify ListTest.java so that after it creates and prints the IntList, it creates and prints a SortedIntList containing the same elements (inserted in the same order). When the list is printed, they should come out in sorted order.

How do I change the order of the items in an arraylist in Java

I have an arraylist. For example
A = [1,2,3,4,5,6,7,8];
I need to change the order of the arraylist so that I can get
A = [2,1,4,3,6,5,8,7]. It means odd position item will be positioned in even positions and vice-versa.
Thanks
A simple approach that assumes
Length of A is given as A.size()
Array A can be accessed by A.get(index) and A.set(index, value)
If your array is not even, the last element is left as-is
Is to swap values in pairs - like this:
for (int index = 1; index < A.size(); index += 2) { // Swap on even indices.
// Swap values at positions index-1 and index.
Object temp = A.get(index-1); // Save value before overwrite.
A.set(index-1, A.get(index)); // First half of swap.
A.set(index, temp); // Final operation for swap.
}
Edit: Changed int to Object, and used A.size, A.get and A.set instead of [] indexers as suggested by comments.
You could do it in the following way:
int a[] = {1,2,3,4,5,6,7,8};
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
for (int i = 0; i < a.length/2; i++) {
int help;
help = a[i*2];
a[i*2]=a[i*2+1];
a[i*2+1] = help;
}
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
Ask if you have questions about the code.
Edit: I missed the arraylist, but the principle is the same.

use an cicle for to add content to an linkedList java

i have this script, but i can't increment
LinkedList<Card> deckOfCards = new LinkedList<Card>();
for (int count = 0; count < deckOfCards.size(); count++) {
deckOfCards[count].add(new Card(Rank.values()[count % 13].toString(),Suit.values()[count / 13].toString(), number[count % 13],Image[count % 52]));
}
i get an error on deckOfCards[count], so my doubt is how i can do this
(The type of the expression must be an array type but it resolved to LinkedList)
i previous code is an array, and works
deckOfCards = new Card[number_cards];
for (int count = 0; count < deckOfCards.length; count++) {
deckOfCards[count] = new Card(Rank.values()[count % 13].toString(),Suit.values()[count / 13].toString(), number[count % 13],Image[count % 52]);
}
}
//suppose to get na name, value of card, but the result is [null, null, null, etc]
public Card[] giveCardPlayer1() {
String name1 = Arrays.toString(deckOfCards);
nameF = name1;
String suit_1 = deckOfCards.toString();
suit1 = suit_1;
return deckOfCards;
}
public int totalValuePlayer1() {
return currentTotal1;
}
public String name1() {
return nameF;
}
public String suit_1() {
return suit1;
}
thanks!!!!
Just call deckOfCards.add(...).
You can't index a Java List the same way you would an array. You have to use its add() method instead. This appends the specified element to the end of the list.
There is also another add() method which takes an int index parameter. However, since lists are not of fixed size, you can't just directly set the nth element of the list by calling deckOfCards.add(count, new Card(...)) - you need to ensure first that the specified element exists in the list, otherwise you get an IndexOutOfBoundsException. It is also worth mentioning that accessing linked lists by index is a slow operation (compared to e.g. ArrayLists) for any list of nontrivial size.
Update
Ah, and you need to fix your loop invariant too. The current version
for (int count = 0; count < deckOfCards.size(); count++) { ...
will never execute the loop body, since the initial size of your list is 0. Change it to
for (int count = 0; count < number_cards; count++) { ...
In addition to Peter's post; if you need to index a list like you try to do here, you can use ArrayList instead.

Categories

Resources