0

I'm trying to add objects to an arraylist in such a way that it'd kind of look like this,

first add
1

second add
1 2

third add
3 1 2

fourth add
3 1 2 4

fifth add
5 3 1 2 4

and this is what I have so far

public deckOfCards() {
    arr = new ArrayList<Card>(); 
}

and

public void add(T cardToAdd) { 

    //reads as position 2
    int middleOfDeck = (arr.size()/2);

    //reads as position 3
    int pos2 = (arr.size()/2)+1; 

    //reads as position 1
    int pos3 = (arr.size()/2)-1; 

    //reads as position 4
    int pos4 = (arr.size()/2)+2; 

    //reads as position 0
    int pos5 = (arr.size()/2)-2; 

    arr.add(middleOfDeck, objToAdd); 
    arr.add(pos2, objToAdd); 
    arr.add(pos3, objToAdd);
    arr.add(pos4, objToAdd); 
    arr.add(pos5, objToAdd); 
}

and this is my test

@Test
public void addTest() {
    DeckOfCards<Cards> bb= new DecckOfCards<Cards>();
    bb.add(new CardType("one", 1));
    bb.add(new CardType("two", 2));
    bb.add(new CardType("three", 3));
    bb.add(new CardType("four", 4));
    bb.add(new CardType("five", 5));


}
1
  • What is your question? Also, you haven't actually explained what you're trying to do. Commented Dec 8, 2016 at 21:27

3 Answers 3

2

Based on your pattern, it looks like you're alternating between inserting at the beginning and end of the list. If so, the logic is very simple:

public void add(T objToAdd) {
    if (arr.size() % 2 == 0) {
        arr.add(0, objToAdd);
    } else {
        arr.add(objToAdd);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much I understand now... so in this line what does the zero mean in words? arr.add(0, objToAdd);
@emmynaki It means insert an item at index 0. See the javadoc for more info.
2

Looking at your examples, it looks like you are trying to add a element at the end if it's value is even or at the beginning if it's odd.

ArrayList<BattleFish> list = new ArrayList<>();

public void add(String name, int id)
{
    if(id % 2 == 0) //if the result of his division by 2 is 0, it's even
        list.add(new BattleFish(name, id));
    else
        list.add(0, new BattleFish(name, id));
}

Hope it helped. You could also use the size of your collection to check if even or odd and set as id the previous size of your collection. This would let you ignore the management of ids and just add elements from strings.

Comments

1

if the number you need to add into the list is even then it will be inserted at the end of the list, if not at begin

private  void myAdd2(int i) {
    if (i % 2 == 0) {
        lis.add(i);
    } else {
        lis.add(0, i);
    }
}

Comments

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.