Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Java программирование > Общие вопросы по Java, Java SE, Kotlin
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 27.06.2018, 18:34   #1
Anton_Jag
Пользователь
 
Регистрация: 05.11.2009
Сообщений: 41
По умолчанию Динамический список массивов-стеков

Подскажите насколько моя реализации соответствует принципам ООП java, что можно добавить, убрать или переделать?
Полная объектная реализация с определением классов для всех элементов реализуемой структуры: информационные объекты, объекты-элементы списка (динамическая реализация), объекты-списки, объект-контейнер
Задача «Структура организации»
информационные объекты: отделы организации (свойства – НазваниеОтдела, ЧислоСотрудников)
отделы объединяются в рамках объекта Филиал (свойство – НазваниеФилиала)
филиалы объединяются в рамках объекта-контейнера Организация (свойство – НазваниеОрганизации)
Код:
package orgdb;
import java.io.Serializable;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrgDB {

   public static class StackArr implements Serializable{
       private final Object[] arr = new Object[100];
       private int count;
   
       public void push(Object elem) {
            arr[count++] = elem;
        }
       public Object pop() {
            return arr[--count];
        }
       public boolean isEmpty() {
            return count == 0;
        }
        public int indexOf(Object elem) {
            for (int i = 0; i < count; i++) {
                if (arr[i] == elem) 
                    return i;
            }
            return -1;
        }
        public Object byIndex(int i){
            if(i < count)
                return arr[i];
            else
                return null;
        }
        public int getCount(){
            return count;
        }
    }
   
    public static class otdel implements Serializable{
        private String name;
        private int count;
        
        public otdel(String name, int count){
            this.name = name;
            this.count = count;
        }
        public void setName(String name){
            this.name = name;
        }
        public void setCount(int count){
            this.count = count;
        }
        public String getName(){
            return name;
        }
        public int getCount(){
            return count;
        }
    }
    
    public static class filial implements Serializable{
        private String name;
        private StackArr otdel;
        
        public filial(String name){
            this.name = name;
            otdel = new StackArr();
        }
        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return name;
        }
        public void pushOtdel(otdel newOtdel){
            this.otdel.push(newOtdel);
        }
        public otdel popOtdel(){
            return (otdel)this.otdel.pop();
        }
        public int getCount(){
            return this.otdel.getCount();
        }
        public otdel byIndex(int i){
            if(i < this.getCount())
                return (otdel)this.otdel.byIndex(i);
            else
                return null;
        }
        public String[] getNamesOtdel(){
            String[] arrName = new String[this.otdel.getCount()];
            otdel temp;
            for(int i = 0; i < arrName.length; i++){
                temp = (otdel)this.otdel.byIndex(i);
                arrName[i] = temp.getName();
            }
            return arrName;
        }
        public int[] getCountsOtdel(){
            int[] arrCount = new int[this.otdel.getCount()];
            otdel temp;
            for(int i = 0; i < arrCount.length; i++){
                temp = (otdel)this.otdel.byIndex(i);
                arrCount[i] = temp.getCount();
            }
            return arrCount;
        }
    }
    
    public static class Organization implements Serializable{
        private String name;
        private StackArr filial;
        Organization next;
        
        public Organization(String name){
            this.name = name;
            filial = new StackArr();
        }
        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return this.name;
        }
        public void pushFilial(filial newFilial){
            this.filial.push(newFilial);
        }
        public filial popFilial(){
            return (filial)this.filial.pop();
        }
        public int getCount(){
            return this.filial.getCount();
        }
        public filial byIndex(int i){
            return (filial)this.filial.byIndex(i);
        }
        public String[] getNamesFilial(){
            String[] arrName = new String[this.getCount()];
            filial temp;
            for(int i = 0; i < arrName.length; i++){
                temp = this.byIndex(i);
                arrName[i] = temp.getName();
            }
            return arrName;
        }
    }
    
    public static class listOrganization implements Serializable{
        private Organization head;
        private Organization tail;
        private int count;
        
        void listOrganization(){
            head = null;
            tail = null;
            count = 0;
        }
        
        public void addFront(Organization a)           
        {
        if(head == null)            
        {                           
            head = a;               
            tail = a;
        }
        else {
            a.next = head;          
            head = a;              
        }
        this.count++;
        }
        public void addBack(Organization a) {          
        if (tail == null)           
        {                           
            head = a;              
            tail = a;
        } else {
            tail.next = a;          
            tail = a;               
        }
        this.count++;
        }
        public String[] getNames(){
            Organization temp = head;
            String[] res = new String[this.count];
            int i = 0;
            while(temp != null){
                res[i] = temp.getName();
                temp = temp.next;
                i++;
            }
            return res;
        }
        public void del(int i){
            Organization temp = head;
            if(i >= this.count) 
                return;
            for(int j=0; j < i - 1; j++)
                temp = temp.next;
            if(temp.next == tail){
                tail = temp;
                temp.next = null;
            }
            else{
                temp.next = temp.next.next;
            }
        }
    }
    
    public static void main(String[] args) throws IOException {
       
        otdel ot1 = new otdel("Ot1", 12);
        otdel ot2 = new otdel("Ot2", 13);
        otdel ot3 = new otdel("Ot3", 14);
        
        filial fil1 = new filial("Fil1");
        filial fil2 = new filial("Fil2");
 
        fil1.pushOtdel(ot1);
        fil1.pushOtdel(ot2);
        fil2.pushOtdel(ot3);
        
        Organization or1 = new Organization("Or1");
        or1.pushFilial(fil1);
        or1.pushFilial(fil2);
        
        listOrganization lo = new listOrganization();
        lo.addBack(or1);
        
        String[] names = lo.getNames();
       
        System.out.println(names[0]);
       try {
           FileOutputStream fos = new FileOutputStream("outOrg.bin");
            try (ObjectOutputStream outStream = new ObjectOutputStream(fos)) {
                outStream.writeObject(or1);
                outStream.flush();
            }
       } catch (IOException ex) {
           Logger.getLogger(OrgDB.class.getName()).log(Level.SEVERE, null, ex);
       }
        
        
    }
    
}
Anton_Jag вне форума Ответить с цитированием
Старый 13.07.2018, 21:41   #2
Bugrimov
C/C++, Java
Участник клуба
 
Аватар для Bugrimov
 
Регистрация: 28.03.2012
Сообщений: 1,680
По умолчанию

Интересно. Я правильно понимаю, ваша задача была описать структуру?
"Keep it simple" - придерживайтесь простоты!
Уильям Оккам - "Не следует множить сущее без необходимости"
Сложность - враг простоты и удобства!
Bugrimov вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Из элементов двух стеков с одинаково упорядоченными элементами собрать новый стек с упорядоченными элементами, изменив связи между элементами стеков (не выделяя новую память). Андрей3636 Паскаль, Turbo Pascal, PascalABC.NET 7 01.11.2017 10:47
C++. Динамический массив массивов символов alextrof94 Общие вопросы C/C++ 4 09.05.2013 00:14
Двусвязный список на основе пары стеков SL1CK Общие вопросы C/C++ 0 05.12.2012 23:26
Динамический список массивов – стеков kitcon Помощь студентам 2 09.05.2011 02:44
Динамический список Sergey240892 Помощь студентам 7 18.04.2011 20:34