Yehudaa פורסם 2009 בנובמבר 20 Share פורסם 2009 בנובמבר 20 public class DataStructure { //create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { //fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { //print out values of even indices of the array InnerEvenIterator iterator = this.new InnerEvenIterator(); while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } }//inner class implements the Iterator pattern private class InnerEvenIterator { //start stepping through the array from the beginning private int next = 0; public boolean hasNext() { //check if a current element is the last in the array return (next <= SIZE - 1); } public int getNext() { //record a value of an even index of the array int retValue = arrayOfInts[next]; //get the next even element next += 2; return retValue; } } public static void main(String s[]) { //fill the array with integer values and print out only values of even indices DataStructure ds = new DataStructure(); ds.printEven(); }}את כל הקוד הבנתי רק השורה הזאת לא ברורה לי InnerEvenIterator iterator = this.new InnerEvenIterator();למי מצביע THIS ? למה יצרו אוביקט ככה ? אפשר היה לוותר על ה THIS ? לא הבנתי בכלל ??? קישור לתוכן שתף באתרים אחרים More sharing options...
etal פורסם 2009 בנובמבר 21 Share פורסם 2009 בנובמבר 21 זו סתם דרך להגיד בצורה מפורשת שה-class שעושים לו new הוא inner class של האובייקט הנוכחי (this). זה נדרש רק אם אם יש ב-package הנוכחי או ב-import אובייקט עם אותו שם כמו ה-inner class אחרת זה מיותר. קישור לתוכן שתף באתרים אחרים More sharing options...
שניצל פורסם 2009 בנובמבר 21 Share פורסם 2009 בנובמבר 21 במקרה הזה זה באמת לא נחוץ, אפשר פשוט לעשות new InnerEvenIterator וזהו.קלאס פנימי שאינו סטטי דורש קלאס "אבא" מהטיפוס שבו הוא הוגדר (במקרה הזה האבא הוא מטיפוס DataStructure). אם אתה קורא ל-new InnerEvenIterator מתוך פונקציה (לא סטטית) של DataStructure, אז כברירת מחדל האבא שלו יהיה this. אבל אם אתה רוצה שה"אבא" שלו לא יהיה this (אלא, נניח, משתנה בשם "other"), אז אתה עושה other.new InnerEvenIterator. זה נחוץ גם אם אתה רוצה לאתחל אובייקט InnerEvenIterator מחוץ לפונקציה של הקלאס DataStrcuture. קישור לתוכן שתף באתרים אחרים More sharing options...
Recommended Posts
ארכיון
דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.