将对象列表转换为队列

huangapple go评论70阅读模式
英文:

Converting an Object list to a Queue

问题

public class ClassOne
{
    static List<ClassTwo> processList = new ArrayList<ClassTwo>();
    public static Queue<ClassTwo> processQueue = new LinkedList<ClassTwo>();

    public static void main(String[] args)
    {
        processList.add(new ClassTwo(1));
        processList.add(new ClassTwo(2));
        processList.add(new ClassTwo(3));

        ConvertToQueue();
    }

    static void ConvertToQueue()
    {
        processQueue.addAll(processList);
    }
}
英文:

How do I convert a List of objects to a Queue and still be able to access their variables?

First I have a main class that creates instance classes of ClassTwo and gives them a unique ID (just hard coded it for the example)

public class ClassOne
{
	static List&lt;ClassTwo&gt; processList = new ArrayList&lt;ClassTwo&gt;();

	public static void main(String[] args)
	{
		processList.add(new Process(1));
		processList.add(new Process(2));
		processList.add(new Process(3));
	}
}

ClassTwo:

public class ClassTwo
{
	int id;

	public ClassTwo(int tempID)
	{
		id = tempID;
	}
}

How would I convert my List to a Queue so that I can still access each object's ID in class one?
I tried something like:

public class ClassOne
{
	static List&lt;Process&gt; processList = new ArrayList&lt;Process&gt;();
	public static Queue&lt;Object&gt; processQueue = new LinkedList&lt;Object&gt;();

	public static void main(String[] args)
	{
		processList.add(new Process(1));
		processList.add(new Process(2));
		processList.add(new Process(3));

		ConvertToQueue();
	}

	ConvertToQueue(List&lt;Process&gt; process)
	{
		//covert here..
	}
}

but I'm not sure exactly how to then convert it to a Queue, so i can still call variable 'id' from each ClassTwo object. Help would be appreciated!

答案1

得分: 1

你可以使用这个:

Queue<Process> queue = new LinkedList<>(processList);

当你这样做时,你仍然可以访问列表中的每个元素,因为它们都是相同的实例。

英文:

You can use this :

Queue&lt;Process&gt; queue = new LinkedList&lt;&gt;(processList);

When you make this, you can still access to every element of the list, because they are all the same instances.

huangapple
  • 本文由 发表于 2020年10月9日 08:35:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64272423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定