Java 如何编写删除方法?
编写一个名为get的方法,该方法将从给定索引返回一个元素。如果索引超出范围,则返回-1 编写一个名为remove的方法,该方法将从给定索引中删除元素。如果索引超出范围,则返回-1。在删除过程中,应相应地移动数据Java 如何编写删除方法?,java,if-statement,for-loop,methods,remove-method,Java,If Statement,For Loop,Methods,Remove Method,编写一个名为get的方法,该方法将从给定索引返回一个元素。如果索引超出范围,则返回-1 编写一个名为remove的方法,该方法将从给定索引中删除元素。如果索引超出范围,则返回-1。在删除过程中,应相应地移动数据 //This is the get method public int get(int index){ if(index < 0 || index >= size) { return -1; }else { return dat
//This is the get method
public int get(int index){
if(index < 0 || index >= size) {
return -1;
}else {
return data[index];
}
}
//This is the remove method
public int remove(int index){
if(index < 0 || index >= size){
return -1;
}else {
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
}
}
//这是get方法
公共整数获取(整数索引){
如果(索引<0 | |索引>=大小){
返回-1;
}否则{
返回数据[索引];
}
}
//这是删除方法
公共整数删除(整数索引){
如果(索引<0 | |索引>=大小){
返回-1;
}否则{
对于(int i=0;i
这就是我所能做到的。不确定如何继续执行代码。如果有人能给我指点迷津,我将不胜感激。谢谢大家! 您需要更换以下部件:
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
for(int i=0;i
与:
for(int i=index;i
- 使用
索引启动循环
不会编译。可能应该是索引[i]
数据[i]
这不会删除最后一个元素。您需要特别检查它。到目前为止,您的想法是正确的。我将根据您的语法假设您正在使用数组。您的
get()
方法看起来不错,但是您的remove()
方法缺少一些代码
public int remove(int index){
//check for out-of-bounds
if(index < 0 || index >= size) //assumes size is set to the size of the array
{
return -1; }
else
{
for(int i = index; i < size-1; i++){
data[i] = data[i+1]; }
data[size-1] = 0; //assuming the array contains numbers, if not replace '0' with null
}
}
public int-remove(int-index){
//检查是否有越界
if(index<0 | | index>=size)//假定size设置为数组的大小
{
返回-1;}
其他的
{
对于(int i=索引;i
公共类MyList{
T[]项=(T[])新对象[10];
公共整数大小(){
int计数器=0;
对于(int i=0;i
您需要发布正在操作的数据结构的代码。索引[i]
??index
不是方法的整数参数而不是数组吗?index[i]应该是数组而不是变量。此外,最后一个元素应该设置为null以避免内存泄漏。
public int remove(int index){
//check for out-of-bounds
if(index < 0 || index >= size) //assumes size is set to the size of the array
{
return -1; }
else
{
for(int i = index; i < size-1; i++){
data[i] = data[i+1]; }
data[size-1] = 0; //assuming the array contains numbers, if not replace '0' with null
}
}
public class MyList<T> {
T[] items = (T[])new Object[10];
public int size() {
int counter=0;
for (int i = 0; i < items.length; i ++) {
if (items[i] != null) {
counter ++;
}
}
return counter;
}
public void remove(int t) {
for (int i = t; i < items.length-1; i++) {
items[i]=items[i+1];
}
items[items.length-1]=null;
items= Arrays.copyOf(items,size());
}
}