简体   繁体   English

Java中没有向量的动态数组

[英]Dynamic arrays without vector in java

import java.util.Scanner;

public class Test {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt();
  int[] v = new int[n];
 }
}

Is there any problem in doing this? 这样做有什么问题吗?

No. (Other than n might be negative, or be huge causing a Denial-of-Service (DoS) condition.) 否。( n以外的值可能为负,或者很大,导致拒绝服务(DoS)条件。)

With arrays you can't change the size later. 使用数组,您以后将无法更改大小。 You have to create a new array, copy the contents and switch all references over. 您必须创建一个新数组,复制内容并切换所有引用。

No, but unlike Vector it is obviously not resizable. 否,但是与Vector不同,它显然不能调整大小。 Note that in Java, all collections are allocated on the heap . 请注意,在Java中,所有集合都分配在heap上

The good thing using class like vector is that it encapsulate all the management you need to do with your array. 使用像vector这样的类的好处是,它封装了您需要对数组进行的所有管理。 So, as Tom Hawtin - tackline said, it would manage unexpected value but it will also manage resize, and it will provide you some usefull method to deal with your array, like .get witch will disallow you to get an item out of bound and many more method you can get there : http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html 因此,正如Tom Hawtin-Tackline所说的那样,它将管理意外的值,但还将管理调整大小,并且它将为您提供一些有用的方法来处理数组,例如.get witch将使您无法获得超出范围的商品,您可以到达那里的更多方法: http : //java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html

btw, as a side note I would recommand you to use an ArrayList : http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html 顺便说一句,作为旁注,我建议您使用ArrayList: http : //java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM