java小知识课堂(一)

1.二维数组

public static void main(String[] args)
	{
		int[] arrOne = new int[3];  // 定义一个1维数组
		arrOne[0] = 1;   // 1维数组的第0个元素赋值为一个整数1
		arrOne[1] = 2;
		arrOne[2] = 3;
		
		int[][] arrTwo = new int[3][4];  // 定义一个2维数组,外围长度为3,里面的每个数组长度为4
		
		arrTwo[0][0] = 1;   // 将二维数组arrTwo的第0个数组的第0个元素赋值为整数1
		arrTwo[0][1] = 2;
		
		arrTwo[1][2] = 6;  // 将二维数组arrTwo的第1个数组的第2个元素赋值为整数6
		
		int[] tmp = {5,5,5,5};
		arrTwo[2] = tmp;   // 将二维数组arrTwo的第2个数组赋值为tmp数组
		
		
		
		int[][] arr3 = new int[3][];   // 定义一个2维数组,外围长度为3,里面的数组长度不定
		
		
		int[][] arr4 = {{1,2,3,4},{5,6},{7,8,9}}; //定义一个2维数组,并且直接赋初值,初值是3个数组
		int a = arr4.length;       // 3
		int b = arr4[0].length;   //  4
		
		for(int[] ls:arr4){
			for(int temp:ls){
				System.out.println(temp);
			}
			System.out.println("");
		}

	}

}

2.三目运算符

public static void main(String[] args)
	{
		int a = 4;
		int b = 5;
		int c = a>b?a:b;
		System.out.println(c);

	}
	输出结果: 5

先比较
先执行1部分的程序,当满足1的条件时,返回2,如果不满足返回3.

3.do-while语句

public static void main(String[] args)
	{
		int i=10;
		do {
			System.out.println("调用do-while方法"+ i);
			i++;
		}while(i<10);
		
		int j=10;
		while(j<10) {
			System.out.println("调用while方法"+ j);
			j++;
		}
		
		
	}

执行结果:
调用do-while方法10
do-while方法,即先执行do内的语句,在执行while

4.匿名内部类

public class AnnonymouseClass {
	
	public static void main(String[] args) {
		
		Person person = new Person();
		person.name = "人";
		
		Chinese chinese = new Chinese();
		chinese.name="铁蛋儿";
		
		/**
		 * 对普通类创建匿名内部类
		 */
		Person p = new Person(){};  //  {} 表示一个匿名内部类的类体   //多态: 用父类的变量来引用子类对象
		
		/*这个就像相当于创建一个子类,只不过因为重写方法的内容逻辑较为简单,
		可以直接以这种方式使用*/
		
		Person p2 = new Person(){
			@Override
			public void say() {
				System.out.println("我是美国人:" + this.name);
			}
		}; 
		p2.name="james bond";
		
		
		
		person.say();
		
		chinese.say();
		
		p2.say();
		
		
		
		/**
		 * 对接口使用匿名内部类创建对象
		 */
		
		ArrayList<Person> pList = new ArrayList<>();
		Collections.sort(pList,new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				
				return 0;
			}
		});
		

collection是一个包,sort是其中的一个方法,需要传入两个参数,一个是需要处理的列表
Comparator是一个接口,后面的{}内的东西,是一个内部类,也就是平常的接口实现类。必须要重写compare方法,因为这个接口是JDK中本身就已经写好的

发布了51 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43316411/article/details/88843482