0

i have two lists they are of type car .

car class has 4 strings variable :

    color;
 model;

//for second

color;
model; 

now i want to join these two lists with out any null cuz first list has :

color="red";
model=null;

second list ;

color=null
model="2010"

so I want them like:

color="red";
model="2010" 

without null

10
  • Where are these lists and why do you say 4 string variables? That looks like 2 per Car. Commented Mar 15, 2014 at 19:59
  • So it seems like there are just two Car objects with 2 strings in there. Where are the lists? Commented Mar 15, 2014 at 20:02
  • list say it called List<Car> cars1; and List<Car> cars2; Commented Mar 15, 2014 at 20:05
  • 1
    Why not construct the code so you don't have those nulls in the first place? Commented Mar 15, 2014 at 20:06
  • 1
    cuz i read it from database and don't know where is the null Commented Mar 15, 2014 at 20:11

1 Answer 1

1

If I understand you correctly, then you want to create a List<Car> that gets the color from one list and the model from the other. To do this, just create new Cars and add them to a new List:

List<Car> newlist = new ArrayList<Car>();
for( int i = 0; i < list1.size() && i < list2.size(); ++i )
    newlist.Add( new Car( list1.get(i).getColor(), list2.get(i).getModel() ) );

However if you do not know which list contains null for each car, you would have to do some checks:

for( int i = 0; i < list1.size() && i < list2.size(); ++i )
{
    String color = list1.get(i).getColor();
    if( color == null )
        color = list2.get(i).getColor();

    String model = list1.get(i).getModel();
    if( model == null )
        model = list2.get(i).getModel();

    newlist.Add( new Car( color, model ) );
}

Note: I assumed Car has a common interface, ie:

class Car
{
    public String getModel(){ return model; }
    public String getColor(){ return color; }
    public Car( String c, String m )
    {
        color = c;
        model = m;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

note that size of list1 not equal list2 so it will get out of index
It won't get out of index, it just won't look at all of them.
if size of list1 is 5 and size of list2 10 then the code will out in i=4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.