日期:2014-05-20 浏览次数:20796 次
import java.util.List;
public interface NameDao {
public List<String> getNameFromArray(String[] names);
public boolean removeFromList(List<String> ListnameList,int id);
}
import java.util.ArrayList;
import java.util.List;
public class NameDaoImpl implements NameDao {
//实现getNameFromArray方法
@Override
public List<String> getNameFromArray(String[] names){
List<String> list=new ArrayList<String>();
//遍历names数组
for (String name:names){
//添加元素
list.add(name);
}
return list;
}
@Override
public boolean removeFromList(List<String> ListnameList,int id)throws IllegalArgumentException{
boolean flag=false;
if(id>=ListnameList.size()
------解决方案--------------------
id<0){
throw new IllegalArgumentException();
}
if(ListnameList.remove(id)!=null){
flag=true;
}
return flag;
}
}
import java.util.List;
public class Test {
public static void main(String[] args) throws IllegalArgumentException{
//创建names数组
String[] names={"张三","李四","王五"};
NameDao nameDao=new NameDaoImpl();
//创建List并赋值
List<String> list=nameDao.getNameFromArray(names);
int id=2;
if(nameDao.removeFromList(list,id)){
System.out.println("删除成功");
}
}
}
package com.test1;
import java.util.List;
public interface NameDao {
// 将数组中的字符串放入列表,该方法需要使用Iterator接口实现,参见课本P558
public List ListgetNameFromArray(String[] names);
// 在列表中搜索到与name相同的项目,就返回该name所在的序号,找不到返回-1。
public int searchName(List nameList, String name);
/*根据指定id,从列表中移除指定的项目,如果id指定错误
(负数或者超出列表最大值)抛出IllegaArgumentException异常,移除成功返回true*/
public boolean removeFromList(List nameList, int id) throws Exception;
}
package com.test1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NameDaoImpl implements NameDao {
public List ListgetNameFromArray(String[] names) {
List<String> list = new ArrayList<String>();
for (String name : names) {
list.add(name);
}
// 使用迭代器输出
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
return list;
}
public int searchName(List nameList, String name) {
for (int i = 0; i < nameList.size(); i++) {
if (name.equals(nameList.get(i))) {
return i;
}
}
return -1;
}
public boolean removeFromList(List nameList, int id) throws Exception{
try {
nameList.remove(id);
return true;