java中foreach怎么访问,Java对象阵列Foreach方法访问
在
PHP開發很長一段時間后,我決定進入Java.在OOP方法和所有這些方面很舒服,我試圖在java中開始這一點,但是我已經掛斷了將我的arraylist對象傳遞給for語句,使用Item類方法打印出來.
HelloInvetory.java
package helloInventory;
import java.util.Arrays;
public class HelloInventory {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
}
Inventory.java
package helloInventory;
import java.util.*;
/**
* Tracks and maintains all items within the inventory
* @author levi
*
*/
public class Inventory {
List InventoryItems = new ArrayList();
/*
* create object from Items class
* and insert into Object[] array.
*/
public void createItemObj(int sku, String name, String descriptor, float price) {
Items item = new Items();
item.setSku(sku);
item.setItemName(name);
item.setItemDescription(descriptor);
item.setItemPrice(price);
this.setInventoryItems(item);
}
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
public void setInventoryItems(Object inventoryItems) {
//InventoryItems.add(inventoryItems);
this.InventoryItems.add(inventoryItems);
}
}
Items.java
package helloInventory;
/**
* Class object to hold each item details
* @author levi
*
*/
public class Items {
int sku;
String itemName;
String itemDescription;
float itemPrice;
public int getSku() {
return sku;
}
public void setSku(int sku) {
this.sku = sku;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public float getItemPrice() {
return itemPrice;
}
public void setItemPrice(float itemPrice) {
this.itemPrice = itemPrice;
}
}
我陷入困境的地方是HelloInventory.java
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
IDE(Eclipse)給出了錯誤“只能迭代數組或java.lang.Iterable的實例”.我需要一些額外的東西,或者我是否在Java中以錯誤的方式解決這個問題?正確的例子會有所幫助.
最好,
列維
總結
以上是生活随笔為你收集整理的java中foreach怎么访问,Java对象阵列Foreach方法访问的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工商信用卡绑定不了工银e生活
- 下一篇: 企业年金什么意思 和基本养老金比哪个更重