ArrayList 显式类型参数字符串可以替换为 <>? [英] ArrayList explicit type argument string can be replaced with <>?

查看:37
本文介绍了ArrayList 显式类型参数字符串可以替换为 <>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是新手!我正在尝试在 Android Studio 上创建一个 arrayList :

a newbie here! I am trying to create an arrayList on Android Studio :

ArrayList<String> family = new ArrayList<String>();

但它给了我一个警告显式类型参数字符串可以用<>替换"和此检查报告所有带有可以用菱形类型<>替换的类型参数的新表达式".我试图忽略它,因为它只是一个警告,但我无法使用.add"向 Arraylist 添加任何元素,所以我假设甚至没有创建 Arraylist.我尝试重新启动 Android Studio 之类的东西,但没有任何效果!感谢您抽出宝贵时间.

but it gives me a warning "Explicit type argument string can be replaced with <>" and "This inspection reports all new expressions with type arguments which can be replaced with diamond type <>". I tried to ignore it because it is just a warning but I couldn't add any elements to the Arraylist using ".add" so I assume the Arraylist wasn't even created. I tried restarting Android Studio and stuff but nothing worked! Thanks for your time.

主要问题是当我使用添加"时,它说它无法解析符号添加".示例:

the main problem is that when I use "add" it said that it cannot resolve symbol 'add'. example :

family.add("jacob");

已解决:感谢大家的回答,我卸载了Android Studio,然后重新安装了它,我不再遇到这个问题了!

SOLVED: Thanks everyone for your answers, I uninstalled Android Studio and then reinstalled it and I am not encountering the problem anymore!

推荐答案

考虑以下(无效)示例...此代码无法编译并出现错误 Cannot resolve symbol add,与您的相同.

Consider the following (invalid) example... this code fails to compile with the error Cannot resolve symbol add, same as yours.

public class Example
{
    ArrayList<String> list = new ArrayList<>();
    list.add("family");
}

第一条语句是合法的——它在最初创建类时声明并初始化列表.但是,第二个语句是不合法的 - 对 add 的调用只能在方法内部进行.

The first statement is legal - it declares and initializes the list when the class is initially created. However, the second statement is not legal - the call to add can only be made from within a method.

这是更正的示例.. 对 add 的调用已移至构造函数(一种特定类型的方法)中,并且编译器不再抱怨 add 不能已解决.

Here's the corrected example.. the call to add has been moved into the constructor (a specific type of method) and the compiler no longer complains that add cannot be resolved.

public class Example
{
    ArrayList<String> list = new ArrayList<>();

    public Example()
    {
        list.add("family");
    }
}

该问题与菱形 <> 运算符无关.正如其他人指出的那样,这是一种语法糖",旨在让编写代码更容易.恕我直言,ArrayList 中的冗余没有任何问题.list = new ArrayList();.我个人的偏好是禁用该特定警告.

The problem has nothing to do with the diamond <> operator. As others have pointed out, this is "syntactic sugar" that is supposed to make writing code easier. IMHO there is nothing wrong with the redundancy in ArrayList<String> list = new ArrayList<String>();. My personal preference would be to disable that particular warning.

这篇关于ArrayList 显式类型参数字符串可以替换为 &lt;&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆