我正在尝试将 Shoe 类型的对象添加到 Shoe 类型的固定数组中,但我遇到了问题。
在 addShoe 方法中,我尝试将 Shoe 类型的引用添加到 sh 数组,如下所示:sh.add(s);
当我尝试运行它时,出现此错误:
无法对数组类型 Shoe[] 调用 add(Shoe) Eclipse 建议我将其更改为“长度”,但它没有意义
我还想我可以编写 addShoes 方法的其他部分,如下所示:
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
if(numShoes<=10){
sh = Arrays.add(s, numShoes);
numShoes++;
}
}
}
It is just one of the ideas. Is it the correct way to do it?
public class TestShoe {<p></p>
<pre><code>public static void main(String[] args) {
ShoeProcessor s = new Shoe();
Shoe s1 = new Shoe(7, "Black");
Shoe s2 = new Shoe(10, "Red");
try {
s.addShoe(s1);
s.addShoe(s2);
}catch(ShoeException bex){
System.out.println("Shoe Exception: " + bex);
}
</code></pre>
<p>}
}</p>
<pre><code>public class ShoeProcessor
{
private Shoe [] sh;
private int numShoes=0;
private ShoeComparator<Shoe> sc;
public ShoeProcessor()
{
sh = new Shoe [10];
sc=new ShoeComparator<Shoe>();
}
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
sh.add(s);
numShoes++;
}
}
}
</code></pre>
<p></p>
感谢您的帮助
我想添加我需要使用固定大小的数组 Shoe。
我还想补充一点,我不想扩展数组 sh。我最多可以向其中添加 10 个 Shoe 类型的引用。这就是为什么我还要计算添加的鞋子数量。
最佳答案
可能我遗漏了一些东西:你想用 sh[numShoes]= s;
替换 sh.add(s);
吗?
关于java - 将引用对象添加到固定数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22105645/