Removing items from custom arraylist implementation - java

I'm working on a custom Arraylist implementation and I have one method where I'm trying to remove an item per conditions from an array such as E[] elements. The array is initialized by doing something like this:
String[] contents = {"chicken", "hippo", "goat"};
ArrayI<String> newarray = new ArrayI(contents);
newarray.chooser(new LongChooser());
It should remove words length 4 or less and return an array like this:
["chicken", "hippo"]
I'm trying not to use any built in methods, like remove(), clone(), arraycopy(), etc. I can't seem to get this to work, I've tried creating a duplicate array and trying to copy elements over like this:
E[] copy = (E[]) (new Object[this.size-1]);
for (int i = 0; i < size; i++) {
if (shorter) {
copy[i] = elements[i];
}
else {
for (int j = i; j<this.size-1; j++) {
elements[j] = elements[j+1];
}
elements[size-1] = null;
size -= 1;
}
for (int i =0; i< copy.length; i++) {
elements[i] = copy[i];
}
size -=1;
I know this is not the correct way because they aren't the same size array and just returns [longword, longerword, null]. Also I'm pretty sure I should be using the size variable, but it doesn't seem to do much.
How do I get this to work? Thanks.

Related

Remove items from custom arraylist implemetation without .remove

I'm working on a custom ArrayList implementation and I have one method where I'm trying to remove an item per conditions from an array such as E[] elements. The array is initialized by doing something like this:
String[] contents = {"chicken", "hippo", "goat"};
ArrayI<String> newarray = new ArrayI(contents);
newarray.chooser(new LongChooser());
It should remove words length 4 or less and return an array like this:
["chicken", "hippo"]
I'm trying not to use any built in methods, like remove(), clone(), arraycopy(), etc. I can't seem to get this to work, I've tried creating a duplicate array and trying to copy elements over like this:
E[] copy = (E[]) (new Object[this.size-1]);
for (int i = 0; i < size; i++) {
if (shorter) {
copy[i] = elements[i];
}
else {
for (int j = i; j<this.size-1; j++) {
elements[j] = elements[j+1];
}
elements[size-1] = null;
size -= 1;
}
for (int i =0; i< copy.length; i++) {
elements[i] = copy[i];
}
size -= 1;
I know this is not the correct way because they aren't the same size array and just returns [longword, longerword, null]. Also I'm pretty sure I should be using the size variable, but it doesn't seem to do much.
How do I get this to work? Thanks.
Create an array to hold the [filtered] results. Its initial size is zero.
Iterate through contents.
If the current element of contents needs to be retained, then
create a temporary array whose length is one greater than the array that holds the results.
copy the results array to the temporary array
set the last element of the temporary array to the current element of contents
assign the temporary array to the results array
Here is the code, using only simple arrays. I presume you can adapt it to your needs. Note that the last line is simply to check the value of newContents. It is not required.
String[] contents = {"chicken", "hippo", "goat"};
String[] newContents = new String[0];
for (String str : contents) {
if (str.length() > 4) {
String[] temp = new String[newContents.length + 1];
for (int i = 0; i < newContents.length; i++) {
temp[i] = newContents[i];
}
temp[newContents.length] = str;
newContents = temp;
}
}
System.out.println(Arrays.toString(newContents));

Suggestions for my Selection Sort / Java

My Selection Sort algorithm is not working.
I am getting the following errors:
//Exception in thread "main" java.lang.NullPointerException
Note: this is for a java class. I do not have a lot of experience. I am done with the assignment. I am trying to understand the reason why my sorting algorithm isn't working.
Any suggestions on how to correct the problem? Tips?
Corrections? ... any help at all will be appreciated.
Here is my code:
private void sortFlowers(String flowerPack[]) {
// TODO: Sort the flowers in the pack (No need to display them here) - Use Selection or Insertion sorts
// NOTE: Special care is needed when dealing with strings! research the compareTo() method with strings
for(int i = 0; i < flowerPack.length; i++){
String currentMinFlow = flowerPack[i];
int minIndex = i;
for(int j = i; j < flowerPack.length; j++){
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){
currentMinFlow = flowerPack[j];
minIndex = j;
}
}
if(minIndex != i){
flowerPack[minIndex] = flowerPack[i];
flowerPack[i] = currentMinFlow;
}
}
}
Exception:
Exception in thread "main" java.lang.NullPointerException at
java.lang.String$CaseInsensitiveComparator.compare(String.java:1181) at
java.lang.String$CaseInsensitiveComparator.compare(String.java:1174) at
java.lang.String.compareToIgnoreCase(String.java:1227) at
Assignment01Driver.sortFlowers(Assignment01Driver.java:112) at
Assignment01Driver.<init>(Assignment01Driver.java:37) at
Assignment01Driver.main(Assignment01Driver.java:5)
The issue is coming from the fact that your array was created with a fixed size.
String[] flowerPack = new String[25];
When you create an array of reference type variables, each variable will be initialized with a value of null. If you call the sortFlowers method before each variable is given a value, you run into an issue.
for(int i = 0; i < flowerPack.length; i++){
String currentMinFlow = flowerPack[i];
In the above segment, you are iterating through all 25 positions in the array, including the values that still have a value of null. Then, the following line causes the error:
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){
Since you are iterating through the entire array, you end up with values of currentMinFlow that are null. If you try to make a method call on a null reference value, you end up with a NullPointerException.
Generally, you rarely want to use fixed size arrays when you're unsure of how many data items you're likely to have. In this case, you would want to use an ArrayList in place of a standard array. An ArrayList is essentially a dynamic array that grows and shrinks as necessary to contain the elements you store in it. This will get rid of your problem with null values, since this will prevent you from having any unused elements in your array.
Replace
String[] flowerPack = new String[25];
with
ArrayList<String> flowerPack = new ArrayList<>();
If you wanted to add or remove a value from the ArrayList you could do
// Add value.
flowerPack.add(value);
// Remove value
flowerPack.remove(value);
If you want to access a certain element in the ArrayList:
String element = flowerPack.get(indexOfElement);
If you want to get the size of the ArrayList:
int size = flowerPack.size();
And if you don't want to modify your sorting method, you can keep it the same by replacing the line
sortFlowers(flowerPack);
with
sortFlowers(flowerPack.toArray(new String[0]));
For an overview of other ArrayList methods and properties, check the online documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
The error says that you are trying to deal with the array that holds a value of null. to understand better, fill in all 25 spots in the array and run the program, it will not give you any error.
Here is the solution that you need.
private void sortFlowers(String flowerPack[])
{
//get the length of the array by counting arrays where the value is not null.
int length = 0;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
length = length + 1;
}
}
//just confirm that the count is correct.
System.out.println(length);
//set the length to the "length" variable as we have found above.
for(int i = 0; i < length; i++)
{
String currentMinFlow = flowerPack[i];
int minIndex = i;
for(int j = i; j < length;j++){
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0)
{
currentMinFlow = flowerPack[j];
minIndex = j;
}
}
if(minIndex != i){
flowerPack[minIndex] = flowerPack[i];
flowerPack[i] = currentMinFlow;
}
}
}
Just replace your sortFlowers method with above code and check.

How to remove object from array

Please bear within as it might be difficult to understand
I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not.
for(int i = 1; i < 51; i++){
if(seat.buttonArray[i] == null){
remove(seat.buttonArray[i]);
seat.buttonArray[i] = null;}
}
There is no way to remove element from array, assuming you want latter indexes changed after remove. For this purpose, you should use List:
Iterator buttonIterator = seat.buttonList.iterator();
while (buttonIterator.hasNext()) {
Object button = buttonIterator.next(); //or more specific type, if your list was generified
if (button == null) { //or some other criteria, wrote this just as an example
buttonIterator.remove();
}
}
If using array is mandatory, you have two options:
Set seat.buttonArray[i] to null value, indicating it has been removed;
Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
You could store the values in a temp array and then copy what you want back into your original array. Somewhat similar to this:
int myArray[50];
int temp[50];
int good;
for (int i = 0; i < 50; i++) {
myArray[i] = i;
}
for (int i = 0; i < 50; i++) {
temp[i] = myArray[i];
}
good = 0;
for (int i = 0; i < 50; i++) {
if (i < 10) {
} else {
myArray[good] = temp[i];
good += 1;
}
}
Looks messier than I first thought... But it essentially does what you're wanting.

how to sort 2d linked list array

I have got a 2d list array to which I am adding characters in a loop like below. I need to be able to sort in lexiographical order each sub container of of the 2d array. Unfortunately, Collections.sort(list) does not work in this case.
List<Character>[][] list = new LinkedList[n][n];
for (int j = 0; j < n; ++j)
{
for (int m = 0; m < 1; m++)
{
// Here is the problem
list[j][m].add(new Character('b'));
// sort the array and continue
}
}
If you want to compare a list of a lists, I suggest you to use the ColumnComparator class:

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Categories