【发布时间】:2021-12-24 18:34:17
【问题描述】:
所以我试图在 java 中创建一个更省时的堆栈实现,但我不知道如何让它更快地工作。这是我的代码:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int[] n = new int[0];
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
n = push(x, n);
System.out.println("ok");
break;
case "pop":
n = pop(n);
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(n.length);
break;
case "back":
back(n);
break;
case "clear":
n = clear();
System.out.println("ok");
break;
}
}
}
static int[] push(int n, int[] x) {
int[] z = new int[x.length + 1];
for (int i = 0; i < x.length; i++){
z[i] = x[i];
}
z[x.length] = n;
return z;
}
static int[] pop(int[] x){
int z[] = new int[x.length-1];
for(int i = 0; i < z.length; i++){
z[i] = x[i];
}
System.out.println(x[x.length-1]);
return z;
}
static void back(int[] x){
System.out.println(x[x.length-1]);
}
static int[] clear(){
int x[] = new int[0];
return x;
}
}
简要说明: 程序从扫描仪中获取值。根据输入的单词,程序会继续执行相应的指令,如推送、弹出、返回……它会打印出预期的值以通过 ok 进行控制台。到目前为止,除了性能外,一切都按预期正常工作。 如您所见,在 push 和 pop 方法中,我的程序创建新数组并复制所采用数组的值 x 并添加 1 个索引和推送值或删除弹出值。这种方法似乎相当缓慢且效率低下。如果不从 java 库中选择 arraylist 或其他类,我找不到更有效的方法。但我必须使用默认整数数组。还有其他问题会恶化程序的性能吗? 如何让我的程序运行得更快?
【问题讨论】:
-
你所说的“更快”是什么意思?你想推多少个数字?唯一/我的IDE抱怨:“使用
System.arraycopy()”,用于push:System.arraycopy(x, 0, z, 0, x.length);(而不是for循环),用于pop:System.arraycopy(x, 0, z, 0, z.length);(而不是for循环;)跨度> -
每次可以将一个元素压入数组。我的目标是使用通用数组,不使用数组复制或从库中导入其他类,并使其工作速度比现在更快
-
当使用“通用数组”时,您还必须区分:
scan.nextXXX(push) ...但arraycopy适用于所有类型的数组(并且比循环更可取)。 .
标签: java arrays data-structures stack