矢量 java 开发,Java矢量容量找到矢量大小

本文介绍了在Java编程中使用Vector类时遇到的ArrayIndexOutOfBoundsException错误,指出问题在于使用了capacity()而不是size()进行迭代。作者建议使用size()替代,并提到了ArrayList作为更优的选择。此外,还展示了如何创建和操作User对象以及在SetOfUsers类中查找用户信息的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am trying to get the contents of a vector.

I have a class which stores user details such as name and password:

package Login;

/**

*

* @author Kutoma

*/

public class User{

private String name;

private String password;

public User(String aName, String password){

name = aName;

this.password = password;

}

public boolean checkPassword(String pass)

{

if(password.equals(pass))

return true;

else

return false;

}

public String getName(){

return name;

}

public String getPassword(){

return password;

}

}

I then have a class called setOfUsers which adds users and finds their names:

package Login;

public class SetOfUsers extends Vector {

private static SetOfUsers register = null;

public SetOfUsers(){

super();

User temp = new User("Adam","12345");

add(temp);

}

public static SetOfUsers getInstance(){

if (register == null)

{ register = new SetOfUsers(); }

return register;

}

public void addUser(User aUser){

super.add(aUser);

}

public User findUserByName(String name)

{

for(int i = 0; i < capacity(); i++){

User user = elementAt(i);

if(user.getName().equals(name)){

return user;

}

}

return null;

}

At the moment I am getting this error java.lang.ArrayIndexOutOfBoundsException: 1 >= 1

However, I have used capacity to find the size of the vector, not sure where I am going wrong here.

My Main program has the following code when login button is clicked it should print out the

user details

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

SetOfUsers register = SetOfUsers.getInstance();

String name = nameText.getText();

User user = register.findUserByName(name);

String passTxt = passText.getText();

user = register.findUserByName(passTxt);

System.out.print(user);

}

解决方案

You're using capacity() which is not the same as size(). See this SO answer for a nice introduction to the differences between the two: https://stackoverflow.com/a/2787405/1370556.

In short, you'll want to loop through size() instead:

for(int i = 0; i < size(); i++){

As an aside, you may want to switch to ArrayLists. Make sure to read up on the differences between Vector and ArrayList in Java: Why is Java Vector class considered obsolete or deprecated?.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值