您的位置:首页 > 编程语言 > Java开发

java学习笔记-数组,对象的拷贝

2011-02-09 20:41 459 查看
数组:
int[] num=new int[3];//声明num变量在栈内存里,new是在堆内存中给对象分配了空间
for(int i=0;i<num.length;i++)
{
System.out.println(num[i]);
}
--------------------------------------------------------------
class Stringtest
{
public static void main(String[] args)
{
Student[] students;
students=new Student[3];
students[0]=new Student("lisi",18);
for(int i=0;i<students.length;i++)
{
System.out.println(students[i]);
}
class Student
{
String name;
int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
}

数组的相关操作:
在Java中,所有的数组都有一个缺省的属性length,用于获取数组中元素的个数
数组的复制:System.arraycopy()
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
数组的排序:Arrays.sort()
在java.util包中。
在已排序的数组中查找某个元素:Arrays.binarySearch(),返回值为int型,是要查找的数组的索引
/*int[] num=new int[]{3,1,2};
Arrays.sort(num);
int index=Arrays.binarySearch(num,3);*/
如果是对对象排序的话sort(Object[] a),All elements in the array must implement the Comparable interface,接口Comparable在java.lang包下

---------------------------------------------------------------------------
import java.util.Arrays;
class ArrayTest1
{
public static void main(String[] args)
{
Student[] ss=new Student[]{new Student("zs",18),
new Student("ls",19),
new Student("ww",20)};
Arrays.sort(ss);
int index=Arrays.binarySearch(ss,new Student("ls",19));
System.out.println("index="+index);
if (index > -1)
{
System.out.println(ss[index]);
}
else
System.out.println("Not Exists");

}
}

class Student implements Comparable
{
int num;
String name;
Student(String name,int num)
{
this.num=num;
this.name=name;
}
public String toString()
{
return "num="+num+","+"name="+name;
}
public int compareTo(Object o)
{
Student s=(Student)o;
//int retsult=num>s.num ? 1 : (num==s.num ? 0 : -1);这是第一种比较方法,下面定义了第二种比较方法
int result=num>s.num ? 1 : (num==s.num ? 0 : -1);
if (result==0)
{
result=name.compareTo(s.name);
}
return result;
}
}
------------------------------------------------------------------------------------

main函数:
public static void main(String[] args)//String是除了那8中以外的类型,所以是引用数组,一开始args并没有被分配空间,它是用来接受命令行参数的。比如在命令行里输入java calssname OtherWords,那么在args里就会保存OtherWords的内容
注:数组本身就是引用类型

如何交换int x,int y的值,而不利用第三个变量:x=x+y;y=x-y;x=x-y;

函数的调用:在Java中,传参时,都是以传值的方法进行。对于基本数据类型,传递的数组的拷贝;对于引用类型,传递的是引用的拷贝

在打印(System.out.println)一个对象的时候,会自动调用这个对象的toString()方法,原Object类中的toString()方法Returns a string representation of the object.It is recommended that all subclasses override this method.

对象的克隆:
为了获取对象的一份拷贝,我们可以利用Object类的clone()方法
在派生类中覆盖基类的clone()方法,并声明为public(因为在Object类中该方法是protected)
在派生类的clone()方法中,调用super.clone()。在运行时刻,Object中的clone()识别出你要复制的是哪一个对象,然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中
在派生类中实现Cloneable接口(没有任何抽象方法,只是为了告诉编译器这个对象可以克隆),否则调用clone()方法会抛出CloneNotSupportedException异常
如果被克隆的对象的数据成员中含有对象,那么就需要作深层次的克隆才能将作为数据成员的对象克隆,否则是把对象变量的值进行了拷贝,即只是把作为数据成员的对象的引用(地址)进行了拷贝。作深层次的克隆,就是要让作为数据成员的对象所属的类也覆盖clone()方法,并且实现Cloneable接口(与被克隆的对象所属的类中的实现方法同)
class Student implements Cloneable
{
String name;
int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();//super.clone()返回的是Object类,根据需要可进行强制类型转换
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}

封装类:(有时函数参数是引用类型,但我们又要传递基本数据类型)
针对八种基本数据类型定义的相应的引用类型——封装类(在java.lang包中定义的,基本数据类型与封装类建立对应关系之后,封装类就是只读类,不能改变)
基本数据类型 封装类
boolean Boolean
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
--------------------------------------------------------------------
class Test
{
public static void main(String[] args)
{
int i=3;
Integer in=new Integer(i);//Integer的一个构造函数Integer(int value)
int j=in.intValue();//int intValue() Returns the value of this Integer as an int
System.out.println("j="+j);
String str=in.toString();//String toString() Returns a String object representing this Integer's value.
System.out.println("str="+str);
String str1="134";//String要是数字类型的
System.out.println(Integer.valueOf(str1));//static Integer valueOf(String s) Returns an Integer object holding the value of the specified String.
//static int parseInt(String s) Parses the string argument as a signed decimal integer.
}
}

Class类(在java.lang包中,Instances of the class Class represent classes and interfaces in a running Java application):
在Java中,每个class都有一个相应的Class对象。也就是说,当我们编写一个类,编译完成后,在生成的.class文件中,就会产生一个Class对象,用于表示这个类的类型信息
获取Class实例的三种方式:
(1)利用对象调用getClass()方法获取该对象的Class实例;
(2)使用Class类的静态方法forName(),用类的名字获取一个Class实例(static Class forName(String className) Returns the Class object associated with the class or interface with the given string name. );
(3)运用.class的方式来获取Class实例,对于基本数据类型的封装类,还可以采用.TYPE来获取相对应的基本数据类型的Class实例
在newInstance()调用类中缺省的构造方法 Object newInstance()(可在不知该类的名字的时候,常见这个类的实例) Creates a new instance of the class represented by this Class object.
在运行期间,如果我们要产生某个类的对象,Java虚拟机(JVM)会检查该类型的Class对象是否已被加载。如果没有被加载,JVM会根据类的名称找到.class文件并加载它。一旦某个类型的Class对象已被加载到内存,就可以用它来产生该类型的所有对象
----------------------------------------------------------------------------------------------------
//获取Class实例的三种方式:
class ClassTest
{
public static void main(String[] args)
{
Point pt=new Point();
Class c1=pt.getClass();
System.out.println(c1.getName());// String getName() Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

try
{
Class c2=Class.forName("Point");//static Class forName(String className) throws ClassNotFoundException Returns the Class object associated with the class or interface with the given string name.
System.out.println(c2.getName());
}
catch(Exception e)
{
e.printStackTrace();
}
Class c3=Point.class;
System.out.println(c3.getName());

Class c4=int.class;
System.out.println(c4.getName());

Class c5=Integer.TYPE;
System.out.println(c5.getName());

Class c6=Integer.class;
System.out.println(c6.getName());

}
}
class Point
{
int x,y;
}
/*结果:
Point
Point
Point
int
int
java.lang.Integer*/
----------------------------------------------------------------------------
//newInstance()调用类中缺省的构造方法:
class anClassTest
{
public static void main(String[] args)
{
if(args.length!=1)
{
return;
}
try
{
Class c=Class.forName(args[0]);
Point pt=(Point)c.newInstance();
pt.output();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Point
{
int x,y;
void output()
{
System.out.println("x="+x+",y="+y);
}
}
class Line
{
int length,x,y;
void output()
{
System.out.println("length="+length+",x="+x+",y="+y);
}
}

?The Reflection API represents,or reflects,the classes,interfaces,and objects in the current Java Virtual Machine.在java.lang.reflect包里

Runtime类(在java.lang包中定义)和Process类
每一个Java程序都有一个Runtime类的单一实例
通过Runtime.getRuntime()获取Runtime类的实例
Runtime类是使用单例模式的一个例子
import java.io.*;
class RuntimeTest
{
public static void main(String[] args)
{
Runtime rt=Runtime.getRuntime();
System.out.println(rt.freeMemory());//long freeMemory():Returns the amount of free memory in the Java Virtual Machine.
System.out.println(rt.totalMemory());// long totalMemory():Returns the total amount of memory in the Java virtual machine.
try
{
rt.exec("notepad");//Process exec(String command):Executes the specified string command in a separate process.
Process p=rt.exec("java anClassTest Point");//现在p就表示java anClassTest这个子进程。类似这种可做图形调用工具
InputStream is=p.getInputStream();
int data;
while((data=is.read())!=-1)
{
System.out.print((char)data);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

设计模式:在我们进行程序设计时,逐渐形成了一些典型问题和问题的解决方案,这就是软件模式。每一个模式描述了一个在我们程序设计中经常发生的问题,以及该问题的解决方案。当我们碰到模式所描述的问题,就可以直接用相应的解决方法去解决这个问题,这就是设计模式
单例模式:
(1)一个类只有一个实例,而且自行实例化并向这个系统提供这个实例,这个类成为单例类
(2)单例类的一个重要的特点就是类的构造方法是私有的,从而避免了外部利用构造方法直接创造多个实例
单例类的实现(比如设计计数器,还有Runtime这个类):
class Singleton
{
private static final Singleton st=new Singleton();//因为为static final,所以在类加载的时候就构造了这个实例
private Singleton(){};
public static Singleton getInstance()
{
reture st;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐