الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

dynamic allocation for array elements

مغلق
بدأه طالبة علم2 في 20 مايو 2003 · 11 رد · 1,059 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم ورحمة الله وبركاته

احتاج الى استخدام array كل مرة بمقاسات مختلفة ، مثلا أحيانا قد أحتاج الى 4 عناصر فقط واحيان أخرى قد أحتاج الى 1000 عنصر .

ومن غير المعقول أن أحجز دائما الحد الأقصى وأنا لن أستخدم الا جزء بسيط فقط .

لذلك لا بد من وجود طريقة تنظم حجز المساحة المطلوبة للمصفوفة ،

استخدمت أمر new ولكنه لم يعمل .

فهل تعرفون كيف يمكنني عمل dynamic allocation ؟؟

وفق الله الجميع لما يحبه ويرضاه .......................

#2

اذا كنتي تقصدين انك لاتعرفين كم طول المصفوفة فانصحك باستخدام linkedlist لان الميزة التي تحتاجينها فيها هي عدم الحاجة الى تحديد الطول ...

كل ماتبغين اضافة عنصر فقط استدعي الميثود add ... وال list راح تتمدد وتتقلص معاك كل ما اضفتي او حذفتي , وهذا هو قمة ال dynamic

اتمنى اني اكون جاوبتك:):)

#3

ListNode

/*
 * File: PhoneListNode.java
 * Author: Java, Java, Java
 * Description: This class defines a node of
 *  a linked list of phone records. It consists
 *  of two parts: a data portion, which stores
 *  a person's name and phone number; and a link
 *  portion, which stores a reference to the next
 *  node in a linked list. 
 */

public class PhoneListNode {
    private String name;
    private String phone;
    private PhoneListNode next;

    /**
     * PhoneListNode() constructor creates a new node
     *  given a person's name and phone number
     * @param s1 -- the person's name
     * @param s2 -- the person's phone number
     */
    public PhoneListNode(String s1, String s2) {
        name = s1;
        phone = s2;
        next = null;
    } // PhoneListNode()

    /**
     * setData() sets the data portion of a node
     *  given a person's name and phone number
     * @param s1 -- the person's name
     * @param s2 -- the person's phone number
     */
    public void setData(String s1, String s2) {
        name = s1;
        phone = s2;
    } // setData()

    /**
     * getName() returns the name portion of the record
     */
    public String getName() {
        return name;
    } // getName()

    /**
     * getData() returns the name and phone number
     */
    public String getData() {
        return name + " " + phone;
    } // getData()

    /**
     * toString() returns a string representation of a
     *  PhoneListNode by overriding Object.toString()
     */
    public String toString() {     
        return name + " " + phone;
    } // toString()

    /**
     * setNext() sets the node's link to the next node
     * @param nextPtr -- a reference (pointer) to a node
     */
    public void setNext(PhoneListNode nextPtr) {
        next = nextPtr;
    } // setNext()

    /**
     * getNext() returns a reference to the next node
     *  following this node
     */
    public PhoneListNode getNext() {
        return next;
    } // getNext()
} // PhoneListNode

List

/*
 * File: PhoneList.java
 * Description:  This class represents a linked
 *  list of telephone records. Each PhoneListNode consists 
 *  phone data and a reference to the next node in the list.
 *  This class defines methods for manipulating the list.
 *  The only data maintained by this class is a reference
 *  to the first node in the list.
 */
public class PhoneList {
    private PhoneListNode head;
    /**
     *  PhoneList() constructor creates an empty list by
     *   setting head to null
     */
    public PhoneList() {
        head = null;         // Start with empty list
    }

    /**
     *  isEmpty() returns true iff the list has no elements
     */
    public boolean isEmpty() {  // Defines an empty list
        return head == null; 
    }

    /**
     *  insert() inserts its parameter at the end of the list
     *  @param newNode -- a reference to the node being inserted
     */
    public void insert(PhoneListNode newNode) {
        if (isEmpty()) 
            head = newNode;                   // Insert at head of list
        else {
            PhoneListNode current = head;     // Start traversal at head
            while (current.getNext() != null) // While not at the last node
                current = current.getNext();  //   go to the next node
            current.setNext( newNode );       // Do the insertion
        }      
    } // insert()

    /**
     *  getPhone() returns the phone number given a person's name
     *  @param name -- a String giving a person's name
     *  Algorithm: Traverse the list until the node containing the
     *   given name is found. Return the corresponding phone number.
     */
    public String getPhone(String name) {
        if (isEmpty())                           // Case 1: empty list
            return "Phone list is empty";
        else {
            PhoneListNode current = head;
            while ((current.getNext() != null) && (!current.getName().equals(name)))
                current = current.getNext();
            if (current.getName().equals(name))  // Case 2: found the name
                return current.getData();
            else                                 // Case 3: no such person
                return ("Sorry. No entry for " + name);           
        }
    } // getPhone()

    /**
     *  remove() removes the node containing the given persons' name
     *  @param name -- a String giving a person's name
     *  Algorithm: Traverse the list until the node containing the
     *   given name is found. Remove that node by adjusting the link
     *   of the preceding node. Note that this requires the list to
     *   be traversed with two pointers, one to the current node
     *   (which may be removed) and one to the previous node.
     */
    public String remove(String name) { // Remove an entry by name
        if (isEmpty())                              // Case 1: empty list
            return "Phone list is empty";
        PhoneListNode current = head;
        PhoneListNode previous = null;
        if (current.getName().equals(name)) {       // Case 2: remove first node
            head = current.getNext();
            return "Removed " + current.toString() ;
        }
        while ((current.getNext() != null) && (!current.getName().equals(name)))  {
            previous = current;
            current = current.getNext();
        }
        if (current.getName().equals(name)) {       // Case 3: remove named node
            previous.setNext(current.getNext());
            return "Removed " + current.toString();
        } else 
            return ("Sorry. No entry for " + name); // Case 4: node not found      
    } // remove()

    /**
     *  print() prints the entire list by traversing it and printing each node
     */
    public void print() {
        if (isEmpty()) 
            System.out.println("Phone list is empty");
        PhoneListNode current = head;                 // Start traversal at head
        while (current != null) {                     // While not at end of list
            System.out.println( current.toString() ); //   print node's data
            current = current.getNext();              //   go to the next node
        }       
    } // print()
    /**
     *  main() creates a PhoneList and test the methods of this class
     */
    public static void main(String argv[]) {
                                // Create list and insert some nodes
        PhoneList list = new PhoneList();          
        list.insert( new PhoneListNode("Ahmed M", "997-0020"));
        list.insert( new PhoneListNode("Omer W", "997-0086"));
        list.insert( new PhoneListNode("Salem P", "997-0010"));
        list.insert( new PhoneListNode("Nuri M", "997-2101"));
        list.insert( new PhoneListNode("Rami K", "997-2517"));
                                // Test whether insertions worked
        System.out.println( "Phone Directory" );
        list.print();
                                // Test whether lookups work
        System.out.println("Looking up numbers by name");
        System.out.println(list.getPhone("Ahmed M")); 
        System.out.println(list.getPhone("Omer P"));
        System.out.println(list.getPhone("Ali K"));
        System.out.println(list.getPhone("Salem P"));
        System.out.println(list.remove("Nuri M"));
        System.out.println("Phone Directory");
        list.print();
                // Test removals, printing list after each removal
        System.out.println(list.remove("Ahmed M"));
        System.out.println("Phone Directory");
        list.print();
        System.out.println(list.remove("Rami K"));
        System.out.println("Phone Directory");
        list.print();
        System.out.println(list.remove("Rami k"));
        System.out.println("Phone Directory");
        list.print();
        System.out.println(list.remove("Ahmed M"));
        System.out.println("Phone Directory");
        list.print();
        System.out.println(list.remove("Ahmed W"));
        System.out.println("Phone Directory");
        list.print();
        System.out.println(list.remove("Ahmed W"));
        System.out.println("Phone Directory");
        list.print();
    } // main()
} // PhoneList

and this is the test class[/ALIGN]


public static void main(String[] args){
PhoneList list = new PhoneList();
list.insert(new PhoneListNode("Ahmed", "055-879-014"));
list.insert(new PhoneListNode("Salah", "054-989-010"));
list.insert(new PhoneListNode("Saled", "056-000-666"));
list.insert(new PhoneListNode("Khaled","052-255-552"));
System.out.println("===========================");
System.out.println("Phone Directory");
list.print();
System.out.println("===========================");
System.out.println("Looking up numbers by name");
System.out.println(list.getPhone("Ahmed"));
System.out.println("===========================");
System.out.println(list.remove("Saled"));
System.out.println("===========================");
System.out.println("Phone Directory");
list.print();
System.out.println("===========================");
list.insert(new PhoneListNode("Saled", "056-000-666"));
System.out.println("Phone Directory after adding Saleh again");
list.print();
System.out.println("===========================");
}
}
public class PhoneListTester{

#4

Use Vector to add any object you want.Call elementAt method to get the object back and do not forget to cast to the object type

Vector v = new Vector();
MyNiceObject obj = new MyNiceObject();
v.add(obj);

//get my nice object back ,must cast
//you must specify the index
obj = (MyNiceObject) v.elementAt(0);

Vector is good for storing shopping cart items in ecommerce applications

Hope this helps

Madani

#5
if you have primary data as int , float,char, double or String then use [];
for example int x[];
x=new int[40];
double y[];
y=new double[30];
 but if you have objects you can use the class Vector or ArrayList
اللهم انا نسألك علما نافعا ونعوذ بك من حماقة الجهلاء
#6

نعم أنا لدي الآن array

وأكتب حاليا الأمر التالي

int[] a1=new int[1000] ;

ولكن بالطبع هذا الأمر غير عملي كما ذكرت سابقا .....

يبدو انني بحاجة فعلا الى التحويل الى linked list

سأجرب ذلك ....

وشكرا لكم جميعا

وفق الله الجميع لما يحبه ويرضاه .......................

#7
this Methd is verey quickly for primary data;

Vector and ArrayList is verygood to use in Java, becuse you can read the data with index and you don't need to init the size for it.

I think that Mr Salah thinks in C++;

;)

اللهم انا نسألك علما نافعا ونعوذ بك من حماقة الجهلاء
#8

As Salah's Program in Vector

i haven't compile it

pacage phonebook;

import java.lang.*;
import java.util.*;


public class PersonItem
{
String name;
String nr;
PersonItem(String name,String nr)
{
  this.name=name;
  this.nr=nr;
} 

 public void printData()
{
System.out.println(name+"t"+nr);
}

}

pacage phonebook;

import java.lang.*;
import java.util.*;
import phonebook.*;

public class Library
{

    public  Vector all_books=null;
    public   Library()
    {
      all_books=new Vector();
    }
    public  void add(PersonItem per)
{
  all_books.add(per);
}

public void listAll()
{
PersonItem p;
for(int i=0;i{
     p=(PersonItem)all_books.elementAt(i);
    p.prinData();


}

}
public static int main(String args[])
{
PersonItem p1=new PersonItem("Khwlani","11111");
PersonItem p2=new PersonItem("Salah","22222");
Library lib=new Library();
lib.add(p1);
lib.add(p2);
lib.listAll();
} 
}
اللهم انا نسألك علما نافعا ونعوذ بك من حماقة الجهلاء
#9

آخر سؤال لو سمحتو ..

ممكن أعمل في الجافا linked list of array صح ؟

يعني يكون كل عنصر من عناصر ال linked list عبارة عن array

وجزيتم خيرا ................

#10

ممكن تسويها لكن

linked list of linked lists وهو الأفضل

وهذا كود لل linked list of array

public class Test{
	public static void main(String[]arg){
		int[] w = new int[2];
		w[0] = 5;
		w[1] = 6;
		java.util.LinkedList le = new java.util.LinkedList();
		le.add(w);
		System.out.println(java.lang.reflect.Array.getInt(le.getFirst(),1));
	}
}
#11

شكرا لك ..

الصراحة هذا أسهل وأبسط من الأكواد السابقة ....

وهو بالضبط اللي أطلبه .....

وفق الله الجميع لما يحبه ويرضاه .................

#12

الأفضل هو الـVector من ناحية الذاكرة وسرعة الوصول.

هذا الموضوع مغلق.

مواضيع مشابهة