范型容器类

举报
吴梦青 发表于 2021/11/30 21:29:02 2021/11/30
【摘要】 范型类 容器类:用来存放对象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

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。