Java 使用可比排序数组
我正在编写一个程序,用户在其中添加一组整数,我必须使用可比较的方法对数组进行排序。以下是我试图做到这一点的方式:Java 使用可比排序数组,java,arrays,comparable,Java,Arrays,Comparable,我正在编写一个程序,用户在其中添加一组整数,我必须使用可比较的方法对数组进行排序。以下是我试图做到这一点的方式: public class Set<E extends Comparable<E>> { String s; String name; private static final int INITIAL_CAPACITY = 10; private E[] theData; private int size = 0; private int capacity =
public class Set<E extends Comparable<E>> {
String s;
String name;
private static final int INITIAL_CAPACITY = 10;
private E[] theData;
private int size = 0;
private int capacity = INITIAL_CAPACITY;
@SuppressWarnings("unchecked")
public Set() {
theData = (E[]) new Comparable[capacity];
}
public Set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void add(E item) {
if (size == capacity) {
reallocate();
}
if(size == 0){
theData[0] = item;
size++;
}
for (int i = 0; i < size; i++) {
int result = item.compareTo(theData[i]);
if (result < 0){
theData[i+1] = theData[i];
theData[i] = item;
size++;
}
if (result > 0){
theData[i+1] = item;
}
}
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return theData[index];
}
public int size() {
return size;
}
private void reallocate() {
capacity = 2 * capacity;
theData = Arrays.copyOf(theData, capacity);
}
}
公共类集合{
字符串s;
字符串名;
专用静态最终int初始容量=10;
私有E[]数据;
私有整数大小=0;
专用int容量=初始容量;
@抑制警告(“未选中”)
公共集(){
数据=(E[])新的可比[容量];
}
公共集(字符串名称){
this.name=名称;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共作废添加(E项){
如果(大小=容量){
重新分配();
}
如果(大小==0){
数据[0]=项目;
大小++;
}
对于(int i=0;i0){
数据[i+1]=项目;
}
}
}
公共E-get(int索引){
如果(索引<0 | |索引>=大小){
将新的ArrayIndex抛出BoundsException(索引);
}
返回数据[索引];
}
公共整数大小(){
返回大小;
}
私有void重新分配(){
容量=2*容量;
theData=Arrays.copyOf(theData,capacity);
}
}
我使用add方法的想法是比较每个添加的项目(添加到集合中的数字)。如果项目小于数据[i]的值,将数据[i]向前移动一点到数据[i+1]中,然后将项目放入数据[i]中
如果大于数据[i]中的值,则将该项放在i+1中,并将较低的值保留在元素i中
我尝试重新编写循环,使用嵌套循环遍历其余元素,但我的逻辑中一定有问题,因为我没有得到更好的结果。每次add方法中的“size”被初始化为“0”,因此for循环不起作用,没有进行比较。
尝试使用
”for(int i=0;这是您不使用数组.排序的一个原因吗?我被指示不要这样做,但当我尝试使用它时,我得到了一个错误:java.util.ComparableTimSort.CountRunAndMakeSenglishing(未知源代码),位于java.util.ComparableTimSort.sort(未知源代码)在java.util.Arrays.sort(未知源代码)中,这有什么问题?具体来说,你在问什么?从我的理解来看,这与使用Arrays.sort和对象数组(我必须使用)有什么关系?看看这个链接,,
public int compare(E o1, E o2) {
return o1.compareTo(o2);
}