gpt4 book ai didi

java - Java实现Sorted List by Array的问题

转载 作者:行者123 更新时间:2023-12-02 00:46:19 24 4
gpt4 key购买 nike

我编写的类的add方法似乎有问题。我想使用数组创建一个SortedList,但我不知道问题出在哪里。这是我的代码:

public class SortedList {

private Integer[] elements;
private int size;
private int capacity;

public SortedList(int cap) {

elements = new Integer[cap];

if (cap > 0)
{
cap = capacity;
}
else
capacity = 10;

}

public boolean isEmpty()
{
return size == 0;
}

public boolean isFull()
{
return size == capacity;
}

public int size()
{
return size;
}

public void doubleCapacity()
{
capacity = capacity * 2;
}

public void add(Integer el)
{
if(this.isEmpty())
{
elements[0] = el;
size++;
}

else if(this.isFull())
{
this.doubleCapacity();
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}

else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}
else
{
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}
else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}

}

public String toString()
{
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}


public static void main(String[] args)
{
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(4);
sl.add(5);
// sl.add(6);
System.out.println(sl.toString());
}



}

如果我只在列表中添加 2 个整数,我的代码就可以工作,但是当我尝试添加数字 3,4,5 时,我会得到 3,5,5...

可能是什么问题?谢谢..

最佳答案

公共(public)类排序列表{

private Integer[] elements;
private int size=0;
private int capacity;

public SortedList(int cap) {

elements = new Integer[cap];

if (cap > 0)
{
capacity = cap;
}
else
capacity = 10;

}

public boolean isEmpty()
{
return size == 0;
}

public boolean isFull()
{
return size == capacity;
}

public int size()
{
return size;
}

public void doubleCapacity()
{
capacity = capacity * 2;
}

public void add(Integer el) throws Exception{
elements[size] = el;
size++;
if(size>capacity){
throw new Exception("Size Exceeded");
}
}

public String toString()
{
sort();
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}

public void sort(){
for (int i=0; i <size()-1; i++) {
if (elements[i] > elements[i+1]) {
// exchange elements
int temp = elements[i];
elements[i] = elements[i+1];
elements[i+1] = temp;
}
}
}

public static void main(String[] args)
{
try {
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(6);
sl.add(5);

//sl.add(6); System.out.println(sl.toString()); } catch (异常前) { Logger.getLogger(SortedList.class.getName()).log(Level.SEVERE, null, ex); } }

}

关于java - Java实现Sorted List by Array的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com