范型容器类
【摘要】 范型类 容器类:用来存放对象ArrayList<String> notes=new ArrayList<String>();容器类有两个类型:容器的类型(eg:ArrayList)元素的类型(eg:<String>)ArrayList of String使用:notes.add(s);//notes.add(10);这样写会出现错误,因为ArrayList of String,括号里只接受...
范型类
容器类:用来存放对象
ArrayList<String> notes=new ArrayList<String>();
容器类有两个类型:
- 容器的类型(eg:ArrayList)
- 元素的类型(eg:<String>)
ArrayList of String
使用:
notes.add(s);
//notes.add(10);这样写会出现错误,因为ArrayList of String,括号里只接受String
Size():通过调用Size()函数可知notes里面放了多少东西。
notes.size();
notes.toArray(a);
把数组填起来
还是昨天的代码,现在需要往里面填东西了。
package notebook;
import java.util.ArrayList;
public class NoteBook {
private ArrayList<String> notes=new ArrayList<String>();
//用来存放String的ArrayList。
//这种类型叫做范型类,这种范型类是一种容器
//notes是对象管理者
public void add(String s) {
notes.add(s);
}
public void add(String s, int location) {
notes.add(location,s);
}
public int getSize() {
return notes.size();
}
public String getNote(int index) {
return notes.get(index);
}
public void removeNote(int index) {
notes.remove(index);
}
public void list() {
String[] a=new String[notes.size()];
// for(int i=0;i<notes.size;i++) {
// a[i]=notes.get(i);
// }
notes.toArray(a);
//把数组填起来
return a;
}
/*public String[] list() {
}*/
public static void main(String[] args) {
NoteBook nb=new NoteBook();//做了个对象
nb.add("first");
nb.add("second");
nb.add("third",1);
System.out.println(nb.getSize());
System.out.println(nb.getNote(0));
System.out.println(nb.getNote(1));
nb.removeNote(1);
String[] a=nb.list();
for(String s:a) {
System.out.println(s);
}
}
}
ArrayList的操作:ArrayList的下标从0开始
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)