将对象列表转换为队列

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

Converting an Object list to a Queue

问题

  1. public class ClassOne
  2. {
  3. static List<ClassTwo> processList = new ArrayList<ClassTwo>();
  4. public static Queue<ClassTwo> processQueue = new LinkedList<ClassTwo>();
  5. public static void main(String[] args)
  6. {
  7. processList.add(new ClassTwo(1));
  8. processList.add(new ClassTwo(2));
  9. processList.add(new ClassTwo(3));
  10. ConvertToQueue();
  11. }
  12. static void ConvertToQueue()
  13. {
  14. processQueue.addAll(processList);
  15. }
  16. }
英文:

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)

  1. public class ClassOne
  2. {
  3. static List&lt;ClassTwo&gt; processList = new ArrayList&lt;ClassTwo&gt;();
  4. public static void main(String[] args)
  5. {
  6. processList.add(new Process(1));
  7. processList.add(new Process(2));
  8. processList.add(new Process(3));
  9. }
  10. }

ClassTwo:

  1. public class ClassTwo
  2. {
  3. int id;
  4. public ClassTwo(int tempID)
  5. {
  6. id = tempID;
  7. }
  8. }

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:

  1. public class ClassOne
  2. {
  3. static List&lt;Process&gt; processList = new ArrayList&lt;Process&gt;();
  4. public static Queue&lt;Object&gt; processQueue = new LinkedList&lt;Object&gt;();
  5. public static void main(String[] args)
  6. {
  7. processList.add(new Process(1));
  8. processList.add(new Process(2));
  9. processList.add(new Process(3));
  10. ConvertToQueue();
  11. }
  12. ConvertToQueue(List&lt;Process&gt; process)
  13. {
  14. //covert here..
  15. }
  16. }

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

你可以使用这个:

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

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

英文:

You can use this :

  1. 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:

确定