[英]How to use a method in java to store information from an arraylist
对于我正在做的项目,我想使用一个单独的类来存储arraylist中各种人的信息。 在这种情况下,该方法将包含一个字符串的arraylist来存储我的所有信息。 当我尝试这样做时,我意识到每次我运行storage
为arraylist添加一个字符串时,它都会从arraylist中删除所有先前的信息。
是否有可能使它成为弦乐Hello, How Are You?
I'm fine. How Are You?
I'm fine. How Are You?
添加到类阵列two
,而无需在阵列重置一次该方法被重新运行?
public class one
{
public static void main (String [] args)
{
two t = new two();
t.storage("Hello, How Are You?");
t.storage("I'm fine. How Are You?");
}
}
import java.util.ArrayList;
public class two
{
public static void storage(String toBeAdded)
{
ArrayList<String> al = new ArrayList<String>();
al.add(toBeAdded);
System.out.println(al);
}
}
给定输出:
[Hello, How Are You?] [I'm fine. How Are You?]
预期产出:
[Hello, How Are You?] [Hello, How Are You?, I'm fine. How Are You?]
有两种方法可以解决您的问题:
选项(1):您当前的ArrayList
范围是storage
方法的本地范围,因为您在每次调用时创建一个new
ArrayList
(到storage()
方法),但您需要的是类级别的static
ArrayList
对象,如下所示,但是因为你正在使用一个对象调用storage()
方法,所以这不是更好的选择(下面会清楚地解释)并且编译器已经发出警告并且你忽略它。
public class two {
private static ArrayList<String> al = new ArrayList<String>();
public static void storage(String toBeAdded)
{
al.add(toBeAdded);
System.out.println(al);
}
}
选项(2)(首选) :删除static
范围并将ArrayList<String>
声明为实例变量,如下所示(首选此选项),因为您使用不需要的对象引用调用static
方法并产生混淆。
public class two {
private ArrayList<String> al = new ArrayList<String>();
public void storage(String toBeAdded)
{
al.add(toBeAdded);
System.out.println(al);
}
}
始终确保使用classname(如Two.storage())调用static
变量/方法而不创建任何对象,因为它们是类级别成员,即它们不适用于单个对象。 我强烈建议你阅读本文并更清楚地理解这个主题。
除了上述重要的一点,请始终确保遵循Java 命名标准,如类名称应以您违反的大写字母开头。
不要将ArrayList声明为局部变量,而是将其用作字段。 也使该方法非静态
public class two
{
private ArrayList<String> al = new ArrayList<String>();
public void storage(String toBeAdded)
{
al.add(toBeAdded);
System.out.println(al);
}
}
你的错误
每次调用storage()
方法时,都会创建一个“ArrayList”的新对象。
解
因此,创建一个类two
的对象,并将其与字符串一起传递给方法storage()
import java.util.ArrayList;
public class one
{
public static void main (String [] args)
{
two t = new two();
t.storage(t,"Hello, How Are You?");
t.storage(t,"I'm fine. How Are You?");
}
}
class two
{
ArrayList<String> al = new ArrayList<String>();
public static void storage(two object,String toBeAdded)
{
object.al.add(toBeAdded);
System.out.println(object.al);
}
}
在类two
中的方法问题storage
你的逻辑是不对的每次调用存储的时间来保存新的字符串创建新的ArrayList的al
,这将删除旧的ArrayList所有以前的信息。
解决那个在第二类中定义static
arraylist并通过方法存储向它添加信息:
public class two
{
public static ArrayList<String> al = new ArrayList<String>();
public void storage(String toBeAdded)
{
al.add(toBeAdded);
System.out.println(al);
}
}
注意 : storage
方法也不应该是static
方法,因为您正在创建类two
对象并通过此对象调用该方法,因此如果您尝试对其进行测试,它将为您提供警告:
访问静态方法存储
原因您试图访问静态方法警告storage
在你的对象t
类two
。
当你在类中声明静态方法时,正确的方法是调用它:
ClassName.MethodName()
在你的例子中:
two.storage("Hello, How Are You?");
two.storage("I'm fine. How Are You?");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.