Julio Diaz
Julio Diaz

Reputation: 9437

getting rid of some elements in 2d array in java

I am building a java function that takes a 2D array and also returns a 2D array. This function filters some elements from the input function. In this case its an array of Strings and it filters the elements that have its second element as 0. For example: If I have the array

{{"one", "0.0"}, {"two", "2.4"}, {"three", "0.0"}, {"four", "2.3"}}

then I will get

{{"two","2.4"},{"four","2.3"}}

I have this but it does not work

public String[][] getArrayNoZero(String[][]s){
  String [] result;
  for(int i=0; i<s.length; i++){
    if(float(s[i][1])>0){
      String []tempArray= {s[i][0],s[i][1]};
      result.append(tempArray);
    }
  }
  return result;
}

Thanks

Upvotes: 0

Views: 610

Answers (3)

donnyton
donnyton

Reputation: 6054

First of all, a String[] for a constant two items is a terrible way to store your data. You'd be better off using an object

public class Pair
{
    public String firstElement;
    public String secondElement;
}

And then you could just have a single array of Pair objects.

Your current implementation simply will not work. Arrays CANNOT dynamically change their size (you are trying to append one array to another). The append() method returns a NEW array that has to be assigned somewhere (you can see why this is so inefficient). So you'd need:

result = result.append(tempArray);

Not to mention that result has to be a 2D array to begin with, which you did not specify in the original code.

String[][] result;

And now you're going to have to initialize result to something to avoid a NullPointerException when you try to use append().

In other words, a 2D array is a terrible way to store this data since you only have 2 columns anyways. Working with structures and a single array of Pair objects is much easier and will save you a lot of headache.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94653

The way you've tried to type cast is not valid. Use Float.parseFloat method to convert string to float or use Equals method to compare a string.

public String[][] getArrayNoZero(String[][]s)
   {
     java.util.List<String[]> result=new java.util.ArrayList<String[]>();
     for(int i=0; i<s.length; i++)
     {
     if(!s[i][1].equals("0.0"))
       {
        String []tempArray= {s[i][0],s[i][1]};
        result.add(tempArray);
       }
     }
    return result.toArray(new String[0][0]);
 }

Upvotes: 2

Vance Maverick
Vance Maverick

Reputation: 822

The simplest way is to build a fresh ArrayList of your desired return type (here, new ArrayList<String[]>), append the desired elements, then use toArray at the end -- return myList.toArray(new String[][0]);.

Upvotes: 0

Related Questions