欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java基础,

来源: javaer 分享于  点击 44286 次 点评:198

Java基础,


在HashMap中键不允许重复。

import java.util.HashMap;


public class Demo2
{

	public static void main(String[] args)
	{
		String str1 = new String("123");
		String str2 = new String("123");
		HashMap<String,String> map = new HashMap<String, String>();
		map.put(str1, "abc");
		System.out.println(map.get(str2));
	}
}

输出结果为abc.

String类型后面跟+表示字符串拼接,字符串于整型相加也为拼接

public class Demo3
{

 public static void main(String[] args)
 {
  String str = "the total is:";
  int i = 10;
  
  System.out.println(str + 20 + i);
  System.out.println((str + 20) + i);
  System.out.println(str + (20 + i));
 }
}



Java中StringBuilder类对象作为参数传递时会创建一个新的StringBulider类对象指向参数对象。

public class Demo4
{

	public static void main(String[] args)
	{
		StringBuilder str1 = new StringBuilder("A");
		StringBuilder str2 = new StringBuilder("B");
		myAppand(str1,str2);
		System.out.println(str1 + "," + str2);
	}
	public static void myAppand(StringBuilder x,StringBuilder y)
	{
		x.append(y);
		y = x;
	}
}


输出结果为AB,B

当调用没有Appand(StringBuilder x,StringBuilder y);方法时会创建两个StringBuilder对象x,y分别指向str1和str所指向的对象。在执行x.append(y)时x和str1指向同一个对象内容变为AB,执行y = x;时y指向x所指向的对象,但是str2并没有指向x所指向的对象。所以str2的内容仍为B;


try finally块中的return语句的处理

public class Demo5
{

	public static void main(String[] args)
	{
		
		Demo5 demo = new Demo5();
		Test test = new Test();
		String str = demo.fun(test);
		System.out.println(str);
		System.out.println(test.str);
		
	}
	public String fun(Test t)
	{
		try{
			t.str += "1";
			return fun2(t);
		}finally
		{
			t.str += "3";
		}
		
		
		
	}
	public String fun2(Test t)
	{
		t.str += "2";
		return t.str;
		
	}
	
	
}

class Test{
	String str = "";
}


输出结果为123 123

如果在try块中存在return语句,则将return的结果暂时存放起来,待finally中的语句执行完再返回结果,finally块可以操作try块中返回语句中的变量。还有一个考察点就是对象作为参数传递,调用fun(Test t)和fun2(Test t)时都会创建新的Test类对象指向test所指向的对象,在使用t改变导致test改变,因为二者指向同一个对象。


关于抽象类与接口

abstract class AbstractTest
{
	int i;final int d = 5;
	abstract void add();
	public int sub(){
		return 0;
	}
	abstract int muti();
	public AbstractTest(){
		
	}
}

以上程序并没有问题,所以抽象类可以有构造方法, 并且抽象类中可以有非抽象的方法并实现。抽象类中可以有成员变量和常量。

interface InterfaceTest1
{

	public InterfaceTest1() //报错,接口不可以有构造方法,因为接口中的方法都必须是抽象方法,不能实现
	{
		
	}
}


接口中不能有构造方法,接口中的方法全部都是抽象方法。接口中可以有常量但不能有成员变量。


关于线程的创建有两种方式:继承Thread类和实现Runnable接口。线程的启动调用start();运行调用run()。


关于equals和hashCode的说法:

如果两个对象调用equals()返回为true,则二者的hashCode相等。如果equals()返回为false则hashCode可能相等也可能不等。



相关文章

    暂无相关文章
相关栏目:

用户点评