gpt4 book ai didi

java - 如何从具有 int 和 string 的 Job 类生成随机对象

转载 作者:行者123 更新时间:2023-12-02 11:19:35 25 4
gpt4 key购买 nike

class Job implements Comparable {

int p;
String name;

public Job(String name, int p) {
this.p = p;
this.name = name;
}


public void execute() {
System.out.println("Execute job:" + name + " - job p=" + p);
}

public int compareTo(Object o) {
Job x = (Job) o;
if (p > x.p) {
return 1;
} else if (p == x.p)
return 0;
else
return -1;
}
public static void main(String[] args) {
Job j1 = new Job("Writer A",3);
Job j2 = new Job("Writer B",2);
Job j3 = new Job("Writer C",1);

PriorityQueue que = new PriorityQueue();
que.offer(j1);
que.offer(j2);
que.offer(j3);

while(que.size()!=0){
Job j = (Job)que.poll();
j.execute();
}
}
}

如何从“Job”类中生成 10 个随机对象,其中包含字段 namep 并将它们添加到我的队列中,直到大小为 20?添加它们应该很容易,但我该怎么做呢?

最佳答案

只需用循环扩展你的 main 方法

public static void main(String[] args) {
Job j1 = new Job("Writer A",3);
Job j2 = new Job("Writer B",2);
Job j3 = new Job("Writer C",1);

PriorityQueue que = new PriorityQueue();
que.offer(j1);
que.offer(j2);
que.offer(j3);

// here you go with a loop
for(int i=0; i<10; i++){
Job job = new Job('Writer ' + i , i);
que.offer(job);
}

while(que.size()!=0){
Job j = (Job)que.poll();
j.execute();
}
}

关于java - 如何从具有 int 和 string 的 Job 类生成随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50027601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com