Jakub Dobrzeniecki
Jakub Dobrzeniecki

Reputation: 31

LinkedList<class> merge with more than 2

I doing small game with pairs of images than need to be paired and I got in to trouble with merging all LinkedList that they object is classes that posses constructor. They store x,y and cropped img. What I can do to merge this lists to one, when node doesn't work. My goal is to have one LinkedList that will shuffle it over the frame.

What I got

enter image description here

and what i try to achive

enter image description here

Can't do this with addAll ,as i have few LinkedList that refer to different classes. Every class have different img and animation to it.

private LinkedList<Odkryte00> os = new LinkedList<Odkryte00>();
    private LinkedList<Odkryte01> os2 = new LinkedList<Odkryte01>();
    private LinkedList<Odkryte02> os3 = new LinkedList<Odkryte02>();
    private LinkedList<Odkryte03> os4 = new LinkedList<Odkryte03>();
    private LinkedList<Odkryte04> os5 = new LinkedList<Odkryte04>();
    private LinkedList<Odkryte05> os6 = new LinkedList<Odkryte05>();

Upvotes: 0

Views: 153

Answers (1)

ViaTech
ViaTech

Reputation: 2813

It sounds like you want to merge multiple LinkedLists together and randomize the items in the combined list so you can shuffle the pieces of the board in the image you show. This is very easy to accomlish in Java and there are already built-in methods to do so using Collections.

Noting from your update

You want to have a LinkedList of various types of objects as your final list, this is still very possible to accomplish using addAll() there just need to be a few edits from what I was showing earlier.

To do this we return:

LinkedList<Object>

From the combineAndShuffle() method I put together earlier, like so:

import java.util.Collections;
import java.util.LinkedList;

public class Test{

    @SafeVarargs
    public static LinkedList<Object> combineAndShuffle(LinkedList<?>... l){
        //must be <Object> because it needs to hold multiple types of objects
        LinkedList<Object> finalList = new LinkedList<>();

        //use <?> wildcard because we are unsure what value we will hit
        for(LinkedList<?> list: l) {
            finalList.addAll(list);
        }
        //shuffle the list
        Collections.shuffle(finalList);

        return finalList;
    }

    public static void main(String [] args){
        //list of strings
        LinkedList<String> listA = new LinkedList<>();
        listA.add("One");
        listA.add("Two");

        //list of integers, so a different class type
        LinkedList<Integer> listB = new LinkedList<>();
        listB.add(3);
        listB.add(4);

        LinkedList<Object> combinedList = combineAndShuffle(listA, listB);
        for(Object item: combinedList)
            System.out.println(item);   
    }
}

Upvotes: 1

Related Questions