我对number
array
中Java
对象中class
删除所有元素有疑问,不建议使用ArrayList ,方法但只是因为它们在数组中的位置
public class Pack {
static int nextNumber = 0;
int number;
String name;
public Pack(String name) {
this.number = ++nextNumber;
this.name = name;
}
@Override
public String toString() {
return "Pack ID:" + number + " - Name: " + name;
}
}
打包
class
class Container {
static int nextNumber = 0;
int number;
int qtPack;
Pack[] packs;
public Container() {
this.number = ++nextNumber;
this.qtPack = 0;
this.packs = new Pack[10];
}
public boolean addPack(Pack pack) {
packs[qtPack] = pack;
qtPack++;
return true;
}
public Pack removePack(int numberPack) {
int idx;
Pack removePack = null;
idx = indexOfPackByID(numberPack);
if (idx != -1) {
removePack = packs[idx];
if (removePack != null) {
for (int i = idx; i < qtPack - 1; i++) {
packs[i] = packs[i + 1];
}
qtPack--;
}
}
return removePack;
}
private int indexOfPackByID(int numberPack) {
for (int i = 0; i < qtPack; i++) {
if ((packs[i] != null)
&& (packs[i].number == numberPack)) {
return i;
}
}
return -1;
}
}
容器
class
public class Main {
public static void main(String[] args) {
Pack[] packs = new Pack[5];
packs[0] = new Pack("A");
packs[1] = new Pack("B");
packs[2] = new Pack("C");
packs[3] = new Pack("D");
packs[4] = new Pack("E");
Container container = new Container();
for (int i = 0; i < packs.length; i++) {
container.addPack(packs[i]);
}
System.out.println("--- PACK IN CONTAINER ---");
for (int i = 0; i < container.qtPack; i++) {
System.out.println(container.packs[i].toString());
}
System.out.println("\n--- REMOVE PACK ---");
for (int i = 0; i < container.qtPack; i++) {
Pack pack = container.removePack(container.packs[i].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
}
}
主要
Main
--- PACK IN CONTAINER ---
Pack ID:1 - Name: A
Pack ID:2 - Name: B
Pack ID:3 - Name: C
Pack ID:4 - Name: D
Pack ID:5 - Name: E
--- REMOVE PACK ---
Remove A - ID: 1
Remove C - ID: 3
Remove E - ID: 5
class FooData(object):
def __init__(self):
...
try:
self.my_cnf = os.environ['HOME'] + '/.my.cnf'
self.my_cxn = mysql.connector.connect(option_files=self.my_cnf)
self.cursor = self.my_cxn.cursor(dictionary=True)
except mysql.connector.Error as err:
if err.errno == 2003:
self.my_cnf = None
self.my_cxn = None
self.cursor = None
任何建议?
答案 0 :(得分:1)
仔细查看Container.removePack()
for (int i = idx; i < qtPack - 1; i++) {
packs[i] = packs[i + 1];
}
每次调用removePack()
时,container
都会将packs[]
的某些元素引用到“下一个”Pack
。因此removePack()
之后pack []不一样。
答案 1 :(得分:1)
你可以从最后删除它们......
for (int i = container.qtPack-1; i >= 0; i--) {
Pack pack = container.removePack(container.packs[i].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
...或总是删除第一个元素:
int count = container.qtPack;
for (int i = 0; i < count; i++) {
Pack pack = container.removePack(container.packs[0].number);
System.out.println("Remove " + pack.name+" - ID: "+pack.number);
}
这是因为通过更改数组,您每次迭代都会更改条件(此处为container.packs
和container.qtPack
)。请记住,每次迭代都会计算循环条件i < container.qtPack
。