类与对象的关系
类
package study;
public class Echo {
//类中实例变量和方法的默认的访问修饰符是public
private int count = 0;//实例变量
public int getCount()//方法getCount()
{
return count;
}
public void setCount(int count)//方法setCount()
{
this.count=count;
}
}
测试类
package study;
import java.util.Scanner;
public class EchoTestDrive
//EchoTestDrive类
{
public static void main(String[] args)
//main方法函数的开始
{
Scanner input =new Scanner(System.in);
Echo echo1;//声明Echo型的对象
echo1=new Echo();//实例化echo1
//echo1.count=2;
//System.out.println(echo1.count);
//由于已经实现了实例变量count的封装,所以不可以直接访问或修改count的值
echo1.setCount(3);
System.out.println(echo1.getCount());
input.close();
}
}
数组
类
package study;
public class Echo {
//数组对象的引用变量
public int[]a;
//为数组变量赋值
public void set(int[]b)
{
a=b;
}
}
测试类
package study;
public class EchoTestDrive
//EchoTestDrive类
{
public static void main(String[] args)
//main方法函数的开始
{
Echo echo1;//声明Echo型的对象
echo1=new Echo();//实例化echo1
int []b=new int[2];
echo1.set(b);//a指向b所指向的数组
int len=echo1.a.length;
System.out.println(len);//2
int []c=new int[3];
echo1.set(c);//a指向c所指向的数组
int len1=echo1.a.length;
System.out.println(len1);//3
b=c;//b指向c所指向的数组
System.out.println(b.length);//3
}
}
数组变量是指向数组的一个引用变量
ArrayList类
import java.util.ArrayList;
public class Test
{
public static void main(String[] args)
{
ArrayList<String> a=new ArrayList<String>();//声明一个ArrayList<String>类型的引用变量a,并将其实例化(即初始化)
String str1="hello";
String str2="b";
//add()用于将特定元素加入到ArrayList中
a.add(str1);
//add(变量名)将变量加入到a集合中
a.add("b");
//add(值)将值b加入到a集合中
//indexof()用于查询特定元素在ArrayList中的位置
int index=a.indexOf(str1);
//查询变量在ArrayList中的位置
System.out.println(index);//0
int index1=a.indexOf("b");
//查询值在ArrayList中的位置
System.out.println(index1);//1
int index2=a.indexOf("c");
System.out.println(index2);//-1 在ArrayList中不存在的元素其索引值为-1
int index3=a.indexOf(str2);
//查询的是str2这个变量的值是否在ArrayList中出现,如果出现则列出其位置,否则得出值为-1
System.out.println(index3);//1
//remove()用于移除ArrayList中的指定元素
a.remove(index1);
//参数为int型时,代表移除ArrayList中对应索引值为此数的元素
a.remove(str1);
//参数为对象时,代表移除ArrayList中对应此对象值的元素
//isEmpty()用于判断ArrayList是否为空,如果为空则返回true,否则返回false
if(a.isEmpty())
{
System.out.println("ArrayList是空的");
}
else
System.out.println("ArrayList并非空的");
}
}
ArrayList类
方法 | 作用 |
---|---|
add() | add()用于将特定元素加入到ArrayList中,括号中可以是变量名也可以是值 |
indexof() | indexof()用于查询特定元素在ArrayList中的位置,括号中可以是变量名也可以是值,在ArrayList中不存在的元素其索引值为-1 |
remove() | remove()用于移除ArrayList中的指定元素, 参数为int型时,代表移除ArrayList中对应索引值为此数的元素;参数为对象时,代表移除ArrayList中对应此对象值的元素 |
isEmpty() | isEmpty()用于判断ArrayList是否为空,如果为空则返回true,否则返回false |