1. System.arrayCopy();
这是由系统提供的一个copy数组的方法,用它可以实现数组内或者数组间的复制。
方法原型为:
public static void ( Object src , int srcPos, Object dest, int destPos, int length);
参数分别为:
src ---- 原数组(即被复制的数组)
dest ---- 目标数组(复制数据的存放位置)
srcPos ---- 从原数组什么位置开始复制
destPos ----目标数组的开始复制位置
length ---- 要复制的数组长度
需要注意的是:原数组和目标数组需要时同一种类型或者可转换的类型。
例如:int [] fun = { 0,1,2,3,4,5,6,7}。
执行方法 System.arrayCopy(fun,0,fun,3,3),
即将数组fun从位置0开始的长度为3的子数组 复制到 自身从位置3开始的长度为3的地方,
所以,复制后的数组fun应为:
int[] fun = {0,1,2,0,1,2,6,7}。
2. foreach
foreach是由java1.5开始增加的一个遍历集合、数组的方法,他和for语句类型,并且两者在许多场景可以相互替换,
其好处就是在一定程度上简化了对集合、数组的遍历。但两者并不能完全替代。
总结:任何foreach语句都可以转化为for语句,但 不是所有的for语句都可以转化为foreach语句。
foreach语句的一般格式为:
for(元素类型 每次循环的类型的变量名 : 循环对象即数据源){
// 循环里面进行的操作
}
比如:
1.遍历数组:
String [] positions = { "beijing", "shanghai" , "guangzhou" , "shenzhen" };
for( String position : positions){
System.out.printIn( name );
}
2.遍历集合:
List<String> lists = new ArrayList();
lists.add( "a" );
lists.add( "b" );
lists.add( "c" );
lists.add( "d" );
for(String str:lists ){
System.out.pritIn( str );
}
另外,总结一下foreach的一些局限性:
1. 使用foreach来遍历集合时,集合必须实现Iterator接口,foreach就是利用Iterator接口来实现对集合的遍历的。
2. 在使用foreach遍历集合时,不能增加或删除集合中的元素。
3. 在使用foreach遍历集合时:当集合中元素类型为基本数据类型时,不能修改集合的值;
当集合中元素类型为对象时,可以改变对象的属性的值,但不能改变对象的引用。
4. 在遍历过程中,要涉及使用集合元素下表index时,不能使用foreach。
1. 使用字符串(string)的分割方法(split())时,注意应该写为:
正确:content.split("\\.") ;
错误:content.split(".") ;
因为字符串string的split方法,传入的分隔字符串是正则表达式,所以好多关键字(比如.[]()\|等)需要转义。
2. 有时候界面弹框(popwindow)需要输入内容时,输入法不弹出,可以做如下处理:
用java代码写:
popupWindow.setFocusable(true);//输入法可弹出
只在xml中设置edittext的focusableInTouchMode属性为true是不可行的:
android:focusableInTouchMode="true"。
频繁使用Collection. contains()方法要使用Set
比如:
错误例子:
ArrayList<Integet> list = other.getList();
for(int i =0;i<=Integer.MAX_VALUE;i++){
list.constains(i);
}
正确写法:
ArrayList<Integet> list = other.getList();
Set<Integer> set = new HashSet(list);
for(int i =0;i<=Integer.MAX_VALUE;i++){
set.constains(i);
}
工具类应该屏蔽public构造函数
比如:
错误写法:
public class MathUtils{
public static final double PI = 3.1415926;
public static int sum(int a, int b){
return a+b;
}
}
正确写法:
public class MathUtils{
// 显式申明private类型的无参构造函数
private MathUtils(){}
public static final double PI = 3.1415926;
public static int sum(int a, int b){
return a+b;
}
}
应为java会为没有明确定义无参构造函数的的类定义一个public类型的无参构造函数,
为避免使用有误,要显式的定义一个private类型的无参构造函数,放置外部实例化。
程序中 EditText 输入身份证号:
1.xml代码设置:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="输入身份证号"
android:inputType="numberSigned"
android:digits="0123456789 Xx"
android:textSize="30dp" />
2.java 代码设置:
String digits = "0123456789Xx";
mContentView.setKeyListener(DigitsKeyListener.getInstance(digits));
3. 使用radiogroup时,如果要重置,使用radiogroup.clearCheck(),不要循环遍历radiobutton,容易出现设置无效。
未完待续。。。