首先,先看一下它们两个的区别:List是一个接口,而ArrayList 是一个类。 ArrayList 继承并实现了List。List list = new ArrayList();这句创建了一个ArrayList的对象后把上溯到了List。此时它是一个List对象了,有些ArrayList有但是List没有的属性和方法,它就不能再用了。而ArrayList list=new ArrayList();创建一对象则保留了ArrayList的所有属性。(摘自360问答)
源代码如下:
MainActivity源代码:
package com.example.arrays_1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) this.findViewById(R.id.btn);
final EditText edit = (EditText) this.findViewById(R.id.et);
//<span style="color: rgb(51, 51, 51); font-family: arial, 'courier new', courier, 宋体, monospace, 'Microsoft YaHei'; font-size: 14px; line-height: 24px; white-space: pre-wrap;">创建了一个ArrayList的对象后把上溯到了List</span>
final List<String> list=new ArrayList<String>();
button.setOnClickListener(new OnClickListener() {
//定义鼠标事件
@Override
public void onClick(View v) {
String a=edit.getText().toString();
if(list.contains(a)){
Toast.makeText(MainActivity.this, "输入的数字已存在", 0).show();
}else if(list.size()>5){
Toast.makeText(MainActivity.this, "最大上限", 0).show();
}else{
list.add(a);
Toast.makeText(MainActivity.this, "已添加", 0).show();
}
}
});
}
}
layout中的源代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入一个数" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="可否输入" />
</LinearLayout>