假定一个txt文件,内容是
45.44,66.78
47.67,69.12
......
内容有重复的,数据项是坐标项。
处理方法:
对于数据内容,定义如下实体类:
public class Point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point(){
x=0;
y=0;
}
public Point(double x,double y){
this.x=x;
this.y=y;
}
public Point(String str){
String[] p=str.split(",");
this.x=Double.valueOf(p[0]);
this.y=Double.valueOf(p[1]);
}
public String print(){
return "<"+this.x+","+this.y+">";
}
//两个点重复,也就是数据项重复,这里需要重写equals方法
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
Point other = (Point) obj;
if (this.getX() == other.getX() && this.getY() == other.getY()) {
return true;
}
return false;
}
}
然后初始化含有重复项的原始数据,并去除:
public List<Point> getPointsList() throws IOException{
List<Point> lst=new ArrayList<Point>();
String txtPath="points.txt";
BufferedReader br=new BufferedReader(new FileReader(txtPath));
String str="";
while((str=br.readLine())!=null && str!=""){
lst.add(new Point(str));
}
br.close();
//过滤重复的Point对象
List<Point> list = new ArrayList<Point>();
for (Object o:lst)
{
if (!list.contains(o))
{
list.add((Point)o);
}
}
return list;
}
这里直接以原始数据作为循环级数,然后每次进行contains判断,比较合理。
如果使用双重循环,就会使得性能下降。
45.44,66.78
47.67,69.12
......
内容有重复的,数据项是坐标项。
处理方法:
对于数据内容,定义如下实体类:
public class Point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point(){
x=0;
y=0;
}
public Point(double x,double y){
this.x=x;
this.y=y;
}
public Point(String str){
String[] p=str.split(",");
this.x=Double.valueOf(p[0]);
this.y=Double.valueOf(p[1]);
}
public String print(){
return "<"+this.x+","+this.y+">";
}
//两个点重复,也就是数据项重复,这里需要重写equals方法
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
Point other = (Point) obj;
if (this.getX() == other.getX() && this.getY() == other.getY()) {
return true;
}
return false;
}
}
然后初始化含有重复项的原始数据,并去除:
public List<Point> getPointsList() throws IOException{
List<Point> lst=new ArrayList<Point>();
String txtPath="points.txt";
BufferedReader br=new BufferedReader(new FileReader(txtPath));
String str="";
while((str=br.readLine())!=null && str!=""){
lst.add(new Point(str));
}
br.close();
//过滤重复的Point对象
List<Point> list = new ArrayList<Point>();
for (Object o:lst)
{
if (!list.contains(o))
{
list.add((Point)o);
}
}
return list;
}
这里直接以原始数据作为循环级数,然后每次进行contains判断,比较合理。
如果使用双重循环,就会使得性能下降。